diff --git a/.github/workflows/prerelease-deps.yml b/.github/workflows/prerelease-deps.yml new file mode 100644 index 000000000000..ba816dddbb25 --- /dev/null +++ b/.github/workflows/prerelease-deps.yml @@ -0,0 +1,186 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: prerelease-deps + +on: + pull_request: + paths: + - '.github/workflows/prerelease-deps.yml' + - 'ci/**' + schedule: + # Run daily at midnight UTC + - cron: '0 0 * * *' + workflow_dispatch: + +permissions: + contents: read + issues: write + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} + cancel-in-progress: true + +env: + PACKAGE_DIRS: packages + NOX_DEFAULT_VENV_BACKEND: "virtualenv" + UV_PRERELEASE: "allow" + # Workaround: Allows libcst/Rust extensions to compile on Python 3.15+ while PyO3 catches up + PYO3_USE_ABI3_FORWARD_COMPATIBILITY: "1" + +jobs: + prerelease: + runs-on: ubuntu-22.04 + strategy: + matrix: + python: ["3.15"] + name: Nightly Pre-release Dependency Issue Reporter (${{ matrix.python }}) + env: + PY_VERSION: ${{ matrix.python }} + FAILURE_LOG_DIR: "/tmp/test_failures" + steps: + - name: Checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + # Use a fetch-depth of 2 to avoid error `fatal: origin/main...HEAD: no merge base` + # See https://github.com/googleapis/google-cloud-python/issues/12013 + # and https://github.com/actions/checkout#checkout-head. + with: + fetch-depth: 2 + persist-credentials: false + + - name: Setup Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ env.PY_VERSION }} + allow-prereleases: true + + - name: Cache pip wheels (including compiled source builds) + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ~/.cache/pip + # Save a fresh cache snapshot for each run so newly compiled wheels are persisted + key: ${{ runner.os }}-pip-prerelease-${{ env.PY_VERSION }}-${{ github.run_id }} + # Restore the most recent cache from previous runs for this Python version + restore-keys: | + ${{ runner.os }}-pip-prerelease-${{ env.PY_VERSION }}- + + - name: Install nox + run: | + pip install nox + + - name: Get handwritten packages to test + id: get-packages + env: + BUILD_TYPE: continuous + TEST_ALL_PACKAGES: "true" + HANDWRITTEN_ONLY: "true" + run: | + python3 ci/get_package_shards.py + + - name: Run prerelease_deps across handwritten packages + id: run-tests + # Do not fail the job when pre-release tests fail; instead, report via GitHub issue below. + continue-on-error: true + env: + BUILD_TYPE: continuous + TEST_TYPE: prerelease + PACKAGE_LIST: ${{ steps.get-packages.outputs.packages }} + NOXFORCEPYTHON: ${{ env.PY_VERSION }} + CONTINUE_ON_ERROR: "true" + PARALLEL_WORKERS: "1" + run: | + ci/run_conditional_tests.sh + + - name: Prepare issue body on failure + if: ${{ steps.run-tests.outcome == 'failure' }} + id: issue-body + run: | + shopt -s nullglob + log_files=("${FAILURE_LOG_DIR}"/*.log.txt) + if [ ${#log_files[@]} -gt 0 ]; then + COUNT=${#log_files[@]} + PKG_LIST="" + DETAILS="" + TRUNCATED_NOTE="" + for log_file in "${log_files[@]}"; do + pkg=$(basename "$log_file" .log.txt) + pip_file="${FAILURE_LOG_DIR}/${pkg}.pip.txt" + log_tail=$(cat "$log_file" 2>/dev/null || echo "Unavailable") + pip_list=$(cat "$pip_file" 2>/dev/null || echo "No dependencies installed (failed during build)") + PKG_LIST="${PKG_LIST}- \`${pkg}\`"$'\n' + + entry=$(cat < + ${pkg} + + **Test Failure Output (last 50 lines):** + \`\`\`text + ${log_tail} + \`\`\` + +
+ Installed Dependencies (pip list) + + \`\`\`text + ${pip_list} + \`\`\` +
+ + EOF + ) + if [ $(( ${#DETAILS} + ${#entry} )) -le 48000 ]; then + DETAILS="${DETAILS}"$'\n'"${entry}"$'\n' + elif [ -z "${TRUNCATED_NOTE}" ]; then + TRUNCATED_NOTE=$'\n\n_Note: Detailed logs for remaining packages were omitted to fit GitHub issue length limits. Please check the workflow run logs for full details._' + fi + done + else + COUNT="unknown" + PKG_LIST="- (Workflow failed outside package test execution)" + DETAILS="" + TRUNCATED_NOTE="" + fi + + echo "::warning title=Pre-release Dependency Failures::Detected pre-release test failures in ${COUNT} package(s). See job summary or GitHub issues for details." + + { + echo "### ⚠️ Pre-release Dependency Failures (${COUNT} packages)" + echo "" + echo "The pre-release check detected failures on Python \`${PY_VERSION}\`:" + echo "" + printf "%s" "${PKG_LIST}" + } >> "$GITHUB_STEP_SUMMARY" + + { + echo "body<> "$GITHUB_OUTPUT" + + - name: Create issue on failure + if: ${{ steps.run-tests.outcome == 'failure' && github.repository == 'googleapis/google-cloud-python' }} + uses: googleapis/librarian/.github/actions/create-issue-on-failure@bb2ee61752bd0f5387195b54c509e4d01a52b41d + with: + title: "prerelease_deps check failed" + labels: "priority: p1,nightly" + body: ${{ steps.issue-body.outputs.body }} diff --git a/.github/workflows/regenerate-all.yml b/.github/workflows/regenerate-all.yml index 0cb57e22db1b..85e64d8c9312 100644 --- a/.github/workflows/regenerate-all.yml +++ b/.github/workflows/regenerate-all.yml @@ -1,14 +1,19 @@ -name: Regenerate all packages after merging to main +name: Regeneration check on: push: branches: - main + pull_request: permissions: contents: read issues: write +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: regenerate: runs-on: ubuntu-latest @@ -19,8 +24,36 @@ jobs: - name: Checkout uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: + fetch-depth: 0 persist-credentials: false + - name: Detect global generator changes + uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 + id: filter + with: + filters: | + global_regen: + - 'librarian.yaml' + - '.librarian/**' + + - name: Setup Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.10" + + - name: Detect changed packages + id: get-packages + if: steps.filter.outputs.global_regen != 'true' && github.event_name == 'pull_request' + env: + BUILD_TYPE: presubmit + TARGET_BRANCH: ${{ github.base_ref }} + TEST_ALL_PACKAGES: ${{ contains(github.event.pull_request.labels.*.name, 'unit_test:all_packages') }} + run: | + if [ -n "$TARGET_BRANCH" ]; then + git fetch --no-tags --quiet origin "$TARGET_BRANCH" || true + fi + python3 ci/get_package_shards.py + - uses: googleapis/librarian@bb2ee61752bd0f5387195b54c509e4d01a52b41d with: protoc-version: "33.5" @@ -34,7 +67,27 @@ jobs: git clone --recurse-submodules --single-branch https://github.com/googleapis/synthtool.git /home/runner/synthtool - name: Regenerate - run: librarian generate -all -v + env: + GLOBAL_REGEN: ${{ steps.filter.outputs.global_regen }} + EVENT_NAME: ${{ github.event_name }} + PACKAGES: ${{ steps.get-packages.outputs.packages }} + run: | + if [ "$GLOBAL_REGEN" = "true" ] || [ "$EVENT_NAME" = "push" ]; then + echo "Running full regeneration..." + librarian generate -all -v + elif [ -n "$PACKAGES" ]; then + for pkg_path in $PACKAGES; do + pkg=$(basename "$pkg_path") + if ! grep -q "^ - name: ${pkg}$" librarian.yaml; then + echo "Skipping $pkg (not in librarian.yaml)..." + continue + fi + echo "Regenerating $pkg..." + librarian generate "$pkg" + done + else + echo "No package changes detected; skipping generation." + fi - name: Check for generated code changes run: | @@ -43,12 +96,12 @@ jobs: echo "==================== GIT DIFF ====================" git diff echo "==================================================" - echo "Regeneration produced code changes! Please run 'librarian generate -all -v' to update the generated files." + echo "Regeneration produced code changes! Please run 'librarian generate' to update the generated files." exit 1 fi - name: Create issue if previous step fails - if: ${{ failure() }} + if: ${{ failure() && github.event_name == 'push' }} uses: googleapis/librarian/.github/actions/create-issue-on-failure@bb2ee61752bd0f5387195b54c509e4d01a52b41d with: title: "Regeneration failed" diff --git a/.github/workflows/spanner-mockserver-tests.yml b/.github/workflows/spanner-mockserver-tests.yml new file mode 100644 index 000000000000..8a15662497ff --- /dev/null +++ b/.github/workflows/spanner-mockserver-tests.yml @@ -0,0 +1,59 @@ +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +on: + pull_request: + paths: + - 'packages/google-cloud-spanner/**' + - '.github/workflows/spanner-mockserver-tests.yml' + push: + branches: + - main + paths: + - 'packages/google-cloud-spanner/**' + - '.github/workflows/spanner-mockserver-tests.yml' + +defaults: + run: + working-directory: packages/google-cloud-spanner + +name: Run Spanner mockserver tests +jobs: + check_changes: + runs-on: ubuntu-latest + outputs: + run_spanner: ${{ steps.filter.outputs.spanner }} + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 + id: filter + with: + filters: | + spanner: + - 'packages/google-cloud-spanner/**' + - '.github/workflows/spanner-mockserver-tests.yml' + + mockserver-tests: + needs: check_changes + if: ${{ needs.check_changes.outputs.run_spanner == 'true' }} + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + - name: Set up Python 3.12 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - name: Install nox + run: python -m pip install nox + - name: Run nox + run: nox -s mockserver diff --git a/.kokoro/continuous/prerelease.cfg b/.kokoro/continuous/prerelease.cfg deleted file mode 100644 index 3595fb43f5c0..000000000000 --- a/.kokoro/continuous/prerelease.cfg +++ /dev/null @@ -1,7 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Only run this nox session. -env_vars: { - key: "NOX_SESSION" - value: "prerelease_deps" -} diff --git a/.kokoro/system.sh b/.kokoro/system.sh index 2b06d445964a..bdb56214026a 100755 --- a/.kokoro/system.sh +++ b/.kokoro/system.sh @@ -57,7 +57,7 @@ run_package_test() { local PROJECT_ID local GOOGLE_APPLICATION_CREDENTIALS local NOX_FILE - # Inherit NOX_SESSION from environment to allow configs (like prerelease.cfg) to pass it in + # Inherit NOX_SESSION from environment to allow configs to pass it in local NOX_SESSION="${NOX_SESSION}" # ISOLATION: Create a unique gcloud config dir for this run @@ -77,9 +77,8 @@ run_package_test() { PROJECT_ID=$(cat "${KOKORO_GFILE_DIR}/google-auth-project-id.json") GOOGLE_APPLICATION_CREDENTIALS="${KOKORO_GFILE_DIR}/google-auth-service-account.json" - # Note: system.sh is also reused for monorepo-wide continuous unit test jobs - # like `core_deps_from_source` and `prerelease_deps`. For google-auth, we only - # want to override NOX_FILE to system_tests/noxfile.py when running actual system tests. + # Note: For google-auth, we only want to override NOX_FILE to system_tests/noxfile.py + # when running actual system tests. if [[ -z "${NOX_SESSION}" || "${NOX_SESSION}" == "system-"* ]]; then NOX_FILE="system_tests/noxfile.py" NOX_SESSION="" diff --git a/.librarian/generator-input/client-post-processing/avoid-double-copyright.yaml b/.librarian/generator-input/client-post-processing/avoid-double-copyright.yaml index 62ebe2843c17..529f029a3720 100644 --- a/.librarian/generator-input/client-post-processing/avoid-double-copyright.yaml +++ b/.librarian/generator-input/client-post-processing/avoid-double-copyright.yaml @@ -60,3 +60,50 @@ replacements: # See the License for the specific language governing permissions and # limitations under the License. count: 2 + - paths: [ + packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2.pyi, + packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2.pyi + ] + before: | + # Copyright 2025 Google LLC + # + # Licensed under the Apache License, Version 2.0 \(the "License"\); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License.\n + # Copyright 2025 Google LLC + # + # Licensed under the Apache License, Version 2.0 \(the "License"\); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + after: | + # Copyright 2025 Google LLC + # + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + count: 2 + diff --git a/.librarian/generator-input/client-post-processing/firestore-integration.yaml b/.librarian/generator-input/client-post-processing/firestore-integration.yaml index 906b9e2eb0e5..d59438c9ff43 100644 --- a/.librarian/generator-input/client-post-processing/firestore-integration.yaml +++ b/.librarian/generator-input/client-post-processing/firestore-integration.yaml @@ -69,6 +69,12 @@ replacements: from google.cloud.firestore_v1.base_pipeline import SubPipeline from google.cloud.firestore_v1.base_query import And, FieldFilter, Or from google.cloud.firestore_v1.batch import WriteBatch + from google.cloud.firestore_v1.bson import ( + BSONInt32, + BSONMaxKey, + BSONMinKey, + BSONObjectId, + ) from google.cloud.firestore_v1.client import Client from google.cloud.firestore_v1.collection import CollectionReference from google.cloud.firestore_v1.document import DocumentReference @@ -170,6 +176,10 @@ replacements: "async_transactional", "AsyncTransaction", "AsyncWriteBatch", + "BSONInt32", + "BSONMaxKey", + "BSONMinKey", + "BSONObjectId", "Client", "CountAggregation", "CollectionGroup", @@ -242,6 +252,10 @@ replacements: AsyncQuery, AsyncTransaction, AsyncWriteBatch, + BSONInt32, + BSONMaxKey, + BSONMinKey, + BSONObjectId, Client, CollectionGroup, CollectionReference, @@ -299,6 +313,10 @@ replacements: "async_transactional", "AsyncTransaction", "AsyncWriteBatch", + "BSONInt32", + "BSONMaxKey", + "BSONMinKey", + "BSONObjectId", "Client", "CountAggregation", "CollectionGroup", diff --git a/.librarian/generator-input/client-post-processing/spanner-integration.yaml b/.librarian/generator-input/client-post-processing/spanner-integration.yaml index 751af40ff368..7b1b268ed15a 100644 --- a/.librarian/generator-input/client-post-processing/spanner-integration.yaml +++ b/.librarian/generator-input/client-post-processing/spanner-integration.yaml @@ -175,6 +175,7 @@ replacements: ] extras = { "libcst": "libcst >= 0.2.5", + "omni": ["cryptography >= 44.0.0"], "test": [ "pytest", "mock", @@ -693,7 +694,9 @@ replacements: UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] UNIT_TEST_DEPENDENCIES: List[str] = [] - UNIT_TEST_EXTRAS: List[str] = [] + UNIT_TEST_EXTRAS: List[str] = [ + "omni", + ] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} SYSTEM_TEST_STANDARD_DEPENDENCIES: List[str] = [ @@ -707,6 +710,7 @@ replacements: SYSTEM_TEST_DEPENDENCIES: List[str] = [] SYSTEM_TEST_EXTRAS: List[str] = [ "tracing", + "omni", ] SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} @@ -1412,6 +1416,7 @@ replacements: mmh3==4.1.0 libcst==0.2.5 googleapis-common-protos==1.69.2 + cryptography==44.0.0 count: 1 - paths: [ packages/google-cloud-spanner/noxfile.py @@ -1432,6 +1437,10 @@ replacements: "auto", "tests/unit", count: 1 + - paths: [packages/google-cloud-spanner/noxfile.py] + before: '\n # Install all dependencies\n session\.install\("-e", "\."\)' + after: '\n # Install all dependencies\n session.install("-e", ".[omni]")' + count: 1 - paths: [packages/google-cloud-spanner/.coveragerc] before: | \[report\] diff --git a/.release-please-bulk-manifest.json b/.release-please-bulk-manifest.json index 5f1d98f623e6..0fcea4ba6e35 100644 --- a/.release-please-bulk-manifest.json +++ b/.release-please-bulk-manifest.json @@ -4,17 +4,17 @@ "packages/django-google-spanner": "5.1.0", "packages/gapic-generator": "1.39.0", "packages/gcp-sphinx-docfx-yaml": "3.3.2", - "packages/google-ads-admanager": "0.10.4", - "packages/google-ads-datamanager": "0.9.2", + "packages/google-ads-admanager": "0.10.5", + "packages/google-ads-datamanager": "0.9.3", "packages/google-ads-marketingplatform-admin": "0.6.0", "packages/google-ai-generativelanguage": "0.12.0", "packages/google-analytics-admin": "0.30.1", - "packages/google-analytics-data": "0.23.0", - "packages/google-api-core": "2.37.0", + "packages/google-analytics-data": "0.23.1", + "packages/google-api-core": "2.38.0", "packages/google-apps-card": "0.7.0", "packages/google-apps-chat": "0.10.5", "packages/google-apps-events-subscriptions": "0.6.0", - "packages/google-apps-meet": "0.5.0", + "packages/google-apps-meet": "0.5.1", "packages/google-apps-script-type": "0.8.0", "packages/google-area120-tables": "0.15.0", "packages/google-auth-httplib2": "0.4.2", @@ -28,7 +28,7 @@ "packages/google-cloud-agentregistry": "0.1.0", "packages/google-cloud-alloydb": "0.11.2", "packages/google-cloud-alloydb-connectors": "0.5.0", - "packages/google-cloud-api-gateway": "1.16.0", + "packages/google-cloud-api-gateway": "1.17.0", "packages/google-cloud-api-keys": "0.9.0", "packages/google-cloud-apigee-connect": "1.16.0", "packages/google-cloud-apihub": "0.7.0", @@ -41,9 +41,9 @@ "packages/google-cloud-asset": "4.4.0", "packages/google-cloud-assured-workloads": "2.4.0", "packages/google-cloud-audit-log": "0.6.2", - "packages/google-cloud-auditmanager": "0.3.1", + "packages/google-cloud-auditmanager": "0.3.2", "packages/google-cloud-automl": "2.20.1", - "packages/google-cloud-backupdr": "0.10.1", + "packages/google-cloud-backupdr": "0.10.2", "packages/google-cloud-bare-metal-solution": "1.14.0", "packages/google-cloud-batch": "0.22.3", "packages/google-cloud-beyondcorp-appconnections": "0.8.0", @@ -53,7 +53,7 @@ "packages/google-cloud-beyondcorp-clientgateways": "0.8.0", "packages/google-cloud-biglake": "0.5.1", "packages/google-cloud-biglake-hive": "0.3.4", - "packages/google-cloud-bigquery": "3.45.1", + "packages/google-cloud-bigquery": "3.45.2", "packages/google-cloud-bigquery-analyticshub": "0.9.0", "packages/google-cloud-bigquery-biglake": "0.8.0", "packages/google-cloud-bigquery-connection": "1.22.0", @@ -64,7 +64,7 @@ "packages/google-cloud-bigquery-migration": "0.15.1", "packages/google-cloud-bigquery-reservation": "1.27.0", "packages/google-cloud-bigquery-storage": "2.41.0", - "packages/google-cloud-bigtable": "2.45.0", + "packages/google-cloud-bigtable": "2.46.0", "packages/google-cloud-billing": "1.20.0", "packages/google-cloud-billing-budgets": "1.21.0", "packages/google-cloud-binary-authorization": "1.19.1", @@ -79,8 +79,8 @@ "packages/google-cloud-commerce-consumer-procurement": "0.6.0", "packages/google-cloud-commerceproducer": "0.1.2", "packages/google-cloud-common": "1.10.0", - "packages/google-cloud-compute": "1.53.0", - "packages/google-cloud-compute-v1beta": "0.12.5", + "packages/google-cloud-compute": "1.54.0", + "packages/google-cloud-compute-v1beta": "0.12.6", "packages/google-cloud-confidentialcomputing": "0.11.1", "packages/google-cloud-config": "0.7.1", "packages/google-cloud-configdelivery": "0.5.0", @@ -105,10 +105,10 @@ "packages/google-cloud-datastream": "1.19.0", "packages/google-cloud-deploy": "2.11.0", "packages/google-cloud-developerconnect": "0.6.0", - "packages/google-cloud-devicestreaming": "0.5.0", + "packages/google-cloud-devicestreaming": "0.5.1", "packages/google-cloud-dialogflow": "2.51.0", "packages/google-cloud-dialogflow-cx": "2.7.0", - "packages/google-cloud-discoveryengine": "0.20.3", + "packages/google-cloud-discoveryengine": "0.20.4", "packages/google-cloud-dlp": "3.39.0", "packages/google-cloud-dms": "1.16.0", "packages/google-cloud-dns": "0.37.1", @@ -124,7 +124,7 @@ "packages/google-cloud-eventarc-publishing": "0.10.1", "packages/google-cloud-filestore": "1.17.1", "packages/google-cloud-financialservices": "0.4.1", - "packages/google-cloud-firestore": "2.30.0", + "packages/google-cloud-firestore": "2.31.0", "packages/google-cloud-functions": "1.24.0", "packages/google-cloud-gdchardwaremanagement": "0.5.1", "packages/google-cloud-geminidataanalytics": "0.13.3", @@ -140,7 +140,7 @@ "packages/google-cloud-iamconnectorcredentials": "0.1.1", "packages/google-cloud-iap": "1.22.0", "packages/google-cloud-ids": "1.14.0", - "packages/google-cloud-kms": "3.16.0", + "packages/google-cloud-kms": "3.17.0", "packages/google-cloud-kms-inventory": "0.6.1", "packages/google-cloud-language": "2.21.0", "packages/google-cloud-licensemanager": "0.4.1", @@ -165,7 +165,7 @@ "packages/google-cloud-network-connectivity": "2.17.0", "packages/google-cloud-network-management": "1.37.0", "packages/google-cloud-network-security": "0.13.3", - "packages/google-cloud-network-services": "0.10.2", + "packages/google-cloud-network-services": "0.10.3", "packages/google-cloud-notebooks": "1.17.0", "packages/google-cloud-optimization": "1.15.0", "packages/google-cloud-oracledatabase": "0.6.2", @@ -183,7 +183,7 @@ "packages/google-cloud-private-catalog": "0.12.1", "packages/google-cloud-privilegedaccessmanager": "0.4.1", "packages/google-cloud-productregistry": "0.1.0", - "packages/google-cloud-pubsub": "2.40.0", + "packages/google-cloud-pubsub": "2.41.0", "packages/google-cloud-quotas": "0.6.2", "packages/google-cloud-rapidmigrationassessment": "0.4.1", "packages/google-cloud-recaptcha-enterprise": "1.33.0", @@ -198,7 +198,7 @@ "packages/google-cloud-saasplatform-saasservicemgmt": "0.7.1", "packages/google-cloud-scheduler": "2.20.0", "packages/google-cloud-secret-manager": "2.30.0", - "packages/google-cloud-securesourcemanager": "0.6.1", + "packages/google-cloud-securesourcemanager": "0.6.2", "packages/google-cloud-security-publicca": "0.7.0", "packages/google-cloud-securitycenter": "1.46.0", "packages/google-cloud-securitycentermanagement": "0.5.0", @@ -254,7 +254,7 @@ "packages/google-maps-places": "0.9.0", "packages/google-maps-routeoptimization": "0.5.0", "packages/google-maps-routing": "0.11.1", - "packages/google-maps-solar": "0.6.0", + "packages/google-maps-solar": "0.6.1", "packages/google-resumable-media": "2.10.2", "packages/google-shopping-css": "0.6.0", "packages/google-shopping-merchant-accounts": "1.6.0", diff --git a/.release-please-individual-manifest.json b/.release-please-individual-manifest.json index 54ce687896b8..f2c7a16c5aa1 100644 --- a/.release-please-individual-manifest.json +++ b/.release-please-individual-manifest.json @@ -3,6 +3,7 @@ "packages/google-cloud-apptopology": "0.1.0", "packages/google-cloud-ftp": "0.1.0", "packages/google-cloud-spanner": "3.71.0", + "packages/google-cloud-spanner-dbapi-driver": "0.0.0", "packages/google-cloud-sql": "0.1.1", "packages/google-cloud-workloadidentity": "0.1.0", "packages/google-crc32c": "1.8.0", diff --git a/ci/get_package_shards.py b/ci/get_package_shards.py index 67ded9e4aa06..d0dd4e7d4ea2 100644 --- a/ci/get_package_shards.py +++ b/ci/get_package_shards.py @@ -148,8 +148,9 @@ def get_packages_to_test(): build_type = os.environ.get("BUILD_TYPE", "presubmit") target_branch = os.environ.get("TARGET_BRANCH", "main") test_all_packages = os.environ.get("TEST_ALL_PACKAGES", "false").lower() == "true" + handwritten_only = os.environ.get("HANDWRITTEN_ONLY", "false").lower() == "true" - all_packages = get_packages() + all_packages = get_packages(handwritten_only=handwritten_only) if test_all_packages: return all_packages diff --git a/ci/run_conditional_tests.sh b/ci/run_conditional_tests.sh index e276b54b2a0d..19a5dd8850a2 100755 --- a/ci/run_conditional_tests.sh +++ b/ci/run_conditional_tests.sh @@ -78,6 +78,14 @@ run_test_in_dir() { local log_file="/tmp/test_log_${PY_VERSION}_${pkg_name_clean}.log" export COVERAGE_FILE="${PROJECT_ROOT}/.coverage.${PY_VERSION}.${pkg_name_clean}" + # Isolate setuptools build directories per worker to prevent parallel build collisions. + local worker_build_dir="/tmp/build_${PY_VERSION}_${pkg_name_clean}" + local dist_cfg="/tmp/dist_cfg_${PY_VERSION}_${pkg_name_clean}.cfg" + mkdir -p "${worker_build_dir}" + printf "[build]\nbuild_base = %s/build\n[bdist_wheel]\nbdist_dir = %s/bdist\n[egg_info]\negg_base = %s\n" \ + "${worker_build_dir}" "${worker_build_dir}" "${worker_build_dir}" > "${dist_cfg}" + export DIST_EXTRA_CONFIG="${dist_cfg}" + local div="============================================================" local header="\n${div}\nRunning tests in ${d}\n${div}" local footer @@ -97,6 +105,8 @@ run_test_in_dir() { set -e popd > /dev/null + rm -rf "${worker_build_dir}" "${dist_cfg}" + if [ ${ret} -ne 0 ]; then footer="❌ Tests failed in ${d} with exit code ${ret}" else @@ -114,13 +124,26 @@ run_test_in_dir() { echo "${footer}" fi + if [ ${ret} -ne 0 ] && [ -n "${FAILURE_LOG_DIR}" ]; then + mkdir -p "${FAILURE_LOG_DIR}" + local pkg_name=$(basename "${d}") + if grep -q "short test summary info" "${log_file}" 2>/dev/null; then + grep -A 35 -B 2 "short test summary info" "${log_file}" 2>/dev/null | sed $'s/\x1b\\[[0-9;]*[a-zA-Z]//g' > "${FAILURE_LOG_DIR}/${pkg_name}.log.txt" || true + else + tail -n 50 "${log_file}" 2>/dev/null | sed $'s/\x1b\\[[0-9;]*[a-zA-Z]//g' > "${FAILURE_LOG_DIR}/${pkg_name}.log.txt" || true + fi + fi + rm -f "${log_file}" if [ ${ret} -ne 0 ]; then + if [ "${CONTINUE_ON_ERROR}" = "true" ]; then + exit 1 + fi exit 255 # Cancel xargs parallel jobs fi } export -f run_test_in_dir -export test_script PROJECT_ROOT PY_VERSION TEST_TYPE +export test_script PROJECT_ROOT PY_VERSION TEST_TYPE CONTINUE_ON_ERROR FAILURE_LOG_DIR dirs_to_test=() diff --git a/ci/run_single_test.sh b/ci/run_single_test.sh index d0dc6f612c0e..ced52a121eae 100755 --- a/ci/run_single_test.sh +++ b/ci/run_single_test.sh @@ -65,7 +65,11 @@ case ${TEST_TYPE} in retval=$? ;; prerelease) - nox -s prerelease_deps-3.14 + if [[ "$(pwd)" == */preview-packages/* ]]; then + echo "Skipping prerelease for preview package $(pwd)" + exit 0 + fi + nox --stop-on-first-error -s prerelease_deps retval=$? ;; core_deps_from_source) @@ -241,9 +245,24 @@ case ${TEST_TYPE} in ;; esac -# Clean up `__pycache__` and `.nox` directories to avoid error -# `No space left on device` seen when running tests in Github Actions +if [ ${retval} -ne 0 ] && [ -n "${FAILURE_LOG_DIR}" ]; then + mkdir -p "${FAILURE_LOG_DIR}" + pkg_name=$(basename "$(pwd)") + for pip_bin in "${NOX_ENVDIR:-.nox}"/*/bin/pip; do + if [ -x "$pip_bin" ]; then + pip_out=$("$pip_bin" list 2>/dev/null || true) + if echo "$pip_out" | grep -qvE "^(Package|-+|pip|setuptools|wheel)[[:space:]]"; then + echo "$pip_out" > "${FAILURE_LOG_DIR}/${pkg_name}.pip.txt" + fi + break + fi + done +fi + +# Clean up `__pycache__`, `.nox`, and build artifact directories to avoid error +# `No space left on device` and prevent leftover build/ files from polluting +# downstream local dependency builds. find . | grep -E "(__pycache__)" | xargs rm -rf -rm -rf .nox +rm -rf .nox build *.egg-info exit ${retval} diff --git a/librarian.yaml b/librarian.yaml index e33e3e95193c..c674197fa11a 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.42.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: 5cbe99334de40143f64b32e805dd8cfe38ef11d5 - sha256: d7703651093e08c99568de99792c2372cb595ab739d01dd6d75254563ab4d7bf + commit: 2820f045329fc1d000570aee6a39226c3382b2e2 + sha256: 2c82a62b685cb73f44c78a5b91d561f83b9bac4a3057dd108e43e61b3cfc0585 tools: pip: - name: black @@ -100,13 +100,13 @@ libraries: python: library_type: OTHER - name: google-ads-admanager - version: 0.10.4 + version: 0.10.5 apis: - path: google/ads/admanager/v1 python: default_version: v1 - name: google-ads-datamanager - version: 0.9.2 + version: 0.9.3 apis: - path: google/ads/datamanager/v1 python: @@ -144,7 +144,7 @@ libraries: metadata_name_override: analyticsadmin default_version: v1alpha - name: google-analytics-data - version: 0.23.0 + version: 0.23.1 apis: - path: google/analytics/data/v1beta - path: google/analytics/data/v1alpha @@ -152,7 +152,7 @@ libraries: metadata_name_override: analyticsdata default_version: v1beta - name: google-api-core - version: 2.37.0 + version: 2.38.0 python: library_type: CORE - name: google-apps-card @@ -182,7 +182,7 @@ libraries: python: default_version: v1 - name: google-apps-meet - version: 0.5.0 + version: 0.5.1 apis: - path: google/apps/meet/v2 - path: google/apps/meet/v2beta @@ -350,7 +350,7 @@ libraries: metadata_name_override: connectors default_version: v1 - name: google-cloud-api-gateway - version: 1.16.0 + version: 1.17.0 apis: - path: google/cloud/apigateway/v1 python: @@ -476,7 +476,7 @@ libraries: metadata_name_override: auditlog default_version: apiVersion - name: google-cloud-auditmanager - version: 0.3.1 + version: 0.3.2 apis: - path: google/cloud/auditmanager/v1 python: @@ -496,9 +496,10 @@ libraries: metadata_name_override: automl default_version: v1 - name: google-cloud-backupdr - version: 0.10.1 + version: 0.10.2 apis: - path: google/cloud/backupdr/v1 + - path: google/cloud/backupdr/v1beta python: metadata_name_override: backupdr default_version: v1 @@ -569,7 +570,7 @@ libraries: python: default_version: v1beta - name: google-cloud-bigquery - version: 3.45.1 + version: 3.45.2 python: library_type: GAPIC_COMBO metadata_name_override: bigquery @@ -663,7 +664,7 @@ libraries: metadata_name_override: bigquerystorage default_version: v1 - name: google-cloud-bigtable - version: 2.45.0 + version: 2.46.0 apis: - path: google/bigtable/v2 - path: google/bigtable/admin/v2 @@ -797,7 +798,7 @@ libraries: metadata_name_override: common default_version: apiVersion - name: google-cloud-compute - version: 1.53.0 + version: 1.54.0 preview: version: 1.51.0-preview.1 apis: @@ -808,7 +809,7 @@ libraries: metadata_name_override: compute default_version: v1 - name: google-cloud-compute-v1beta - version: 0.12.5 + version: 0.12.6 apis: - path: google/cloud/compute/v1beta python: @@ -1015,7 +1016,7 @@ libraries: python: default_version: v1 - name: google-cloud-devicestreaming - version: 0.5.0 + version: 0.5.1 apis: - path: google/cloud/devicestreaming/v1 python: @@ -1047,7 +1048,7 @@ libraries: metadata_name_override: dialogflow-cx default_version: v3 - name: google-cloud-discoveryengine - version: 0.20.3 + version: 0.20.4 apis: - path: google/cloud/discoveryengine/v1 - path: google/cloud/discoveryengine/v1beta @@ -1173,7 +1174,7 @@ libraries: python: default_version: v1 - name: google-cloud-firestore - version: 2.30.0 + version: 2.31.0 apis: - path: google/firestore/v1 - path: google/firestore/admin/v1 @@ -1374,7 +1375,7 @@ libraries: metadata_name_override: ids default_version: v1 - name: google-cloud-kms - version: 3.16.0 + version: 3.17.0 apis: - path: google/cloud/kms/v1 python: @@ -1582,13 +1583,16 @@ libraries: metadata_name_override: networksecurity default_version: v1 - name: google-cloud-network-services - version: 0.10.2 + version: 0.10.3 apis: - path: google/cloud/networkservices/v1 + - path: google/cloud/networkservices/v1beta1 python: opt_args_by_api: google/cloud/networkservices/v1: - python-gapic-name=network_services + google/cloud/networkservices/v1beta1: + - python-gapic-name=network_services metadata_name_override: networkservices default_version: v1 - name: google-cloud-notebooks @@ -1737,7 +1741,7 @@ libraries: python: default_version: v1 - name: google-cloud-pubsub - version: 2.40.0 + version: 2.41.0 apis: - path: google/pubsub/v1 python: @@ -1861,7 +1865,7 @@ libraries: metadata_name_override: secretmanager default_version: v1 - name: google-cloud-securesourcemanager - version: 0.6.1 + version: 0.6.2 apis: - path: google/cloud/securesourcemanager/v1 python: @@ -2000,6 +2004,10 @@ libraries: - python-gapic-name=spanner metadata_name_override: spanner default_version: v1 + - name: google-cloud-spanner-dbapi-driver + version: 0.0.0 + python: + library_type: INTEGRATION - name: google-cloud-speech version: 2.40.0 apis: @@ -2428,7 +2436,7 @@ libraries: metadata_name_override: routing default_version: v2 - name: google-maps-solar - version: 0.6.0 + version: 0.6.1 apis: - path: google/maps/solar/v1 python: diff --git a/packages/google-ads-admanager/CHANGELOG.md b/packages/google-ads-admanager/CHANGELOG.md index bcf46f96d666..aa2711bb5690 100644 --- a/packages/google-ads-admanager/CHANGELOG.md +++ b/packages/google-ads-admanager/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-ads-admanager/#history +## [0.10.5](https://github.com/googleapis/google-cloud-python/compare/google-ads-admanager-v0.10.4...google-ads-admanager-v0.10.5) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.10.4](https://github.com/googleapis/google-cloud-python/compare/google-ads-admanager-v0.10.3...google-ads-admanager-v0.10.4) (2026-09-14) diff --git a/packages/google-ads-admanager/docs/admanager_v1/dai_session_service.rst b/packages/google-ads-admanager/docs/admanager_v1/dai_session_service.rst new file mode 100644 index 000000000000..d547cd4dd304 --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/dai_session_service.rst @@ -0,0 +1,6 @@ +DaiSessionService +----------------------------------- + +.. automodule:: google.ads.admanager_v1.services.dai_session_service + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/services_.rst b/packages/google-ads-admanager/docs/admanager_v1/services_.rst index 021173521c6a..61c1061eec98 100644 --- a/packages/google-ads-admanager/docs/admanager_v1/services_.rst +++ b/packages/google-ads-admanager/docs/admanager_v1/services_.rst @@ -31,6 +31,7 @@ Services for Google Ads Admanager v1 API custom_targeting_value_service dai_authentication_key_service dai_encoding_profile_service + dai_session_service device_capability_service device_category_service device_manufacturer_service diff --git a/packages/google-ads-admanager/google/ads/admanager/__init__.py b/packages/google-ads-admanager/google/ads/admanager/__init__.py index ff6f9c0012a8..f5c68a69ab9d 100644 --- a/packages/google-ads-admanager/google/ads/admanager/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager/__init__.py @@ -88,6 +88,9 @@ from google.ads.admanager_v1.services.dai_encoding_profile_service.client import ( DaiEncodingProfileServiceClient, ) +from google.ads.admanager_v1.services.dai_session_service.client import ( + DaiSessionServiceClient, +) from google.ads.admanager_v1.services.device_capability_service.client import ( DeviceCapabilityServiceClient, ) @@ -683,6 +686,23 @@ ListDaiEncodingProfilesResponse, UpdateDaiEncodingProfileRequest, ) +from google.ads.admanager_v1.types.dai_session_enums import ( + AdBreakFindingTypeEnum, + AdRequestFindingTypeEnum, + AdResponseTypeEnum, + BreakTypeEnum, + CreativeFindingTypeEnum, + CreativeIdTypeEnum, + PodFindingTypeEnum, + PrefetchStageTypeEnum, + ReportingTypeEnum, + SessionFindingSeverityEnum, + SlateFindingTypeEnum, + StitchingTypeEnum, + TrackingPingFindingTypeEnum, +) +from google.ads.admanager_v1.types.dai_session_messages import DaiSession +from google.ads.admanager_v1.types.dai_session_service import GetDaiSessionRequest from google.ads.admanager_v1.types.deal_buyer_permission_type_enum import ( DealBuyerPermissionTypeEnum, ) @@ -1261,6 +1281,7 @@ "CustomTargetingValueServiceClient", "DaiAuthenticationKeyServiceClient", "DaiEncodingProfileServiceClient", + "DaiSessionServiceClient", "DeviceCapabilityServiceClient", "DeviceCategoryServiceClient", "DeviceManufacturerServiceClient", @@ -1675,6 +1696,21 @@ "ListDaiEncodingProfilesRequest", "ListDaiEncodingProfilesResponse", "UpdateDaiEncodingProfileRequest", + "AdBreakFindingTypeEnum", + "AdRequestFindingTypeEnum", + "AdResponseTypeEnum", + "BreakTypeEnum", + "CreativeFindingTypeEnum", + "CreativeIdTypeEnum", + "PodFindingTypeEnum", + "PrefetchStageTypeEnum", + "ReportingTypeEnum", + "SessionFindingSeverityEnum", + "SlateFindingTypeEnum", + "StitchingTypeEnum", + "TrackingPingFindingTypeEnum", + "DaiSession", + "GetDaiSessionRequest", "DealBuyerPermissionTypeEnum", "DealPriorityTierEnum", "CompanionDeliveryOptionEnum", diff --git a/packages/google-ads-admanager/google/ads/admanager/gapic_version.py b/packages/google-ads-admanager/google/ads/admanager/gapic_version.py index a59dfd670715..0f411675b722 100644 --- a/packages/google-ads-admanager/google/ads/admanager/gapic_version.py +++ b/packages/google-ads-admanager/google/ads/admanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.4" # {x-release-please-version} +__version__ = "0.10.5" # {x-release-please-version} diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py index edc03e95add3..75fcf1616db3 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py @@ -54,6 +54,7 @@ "google.ads.admanager_v1.services.custom_targeting_value_service", "google.ads.admanager_v1.services.dai_authentication_key_service", "google.ads.admanager_v1.services.dai_encoding_profile_service", + "google.ads.admanager_v1.services.dai_session_service", "google.ads.admanager_v1.services.device_capability_service", "google.ads.admanager_v1.services.device_category_service", "google.ads.admanager_v1.services.device_manufacturer_service", @@ -186,6 +187,9 @@ "google.ads.admanager_v1.types.dai_encoding_profile_enums", "google.ads.admanager_v1.types.dai_encoding_profile_messages", "google.ads.admanager_v1.types.dai_encoding_profile_service", + "google.ads.admanager_v1.types.dai_session_enums", + "google.ads.admanager_v1.types.dai_session_messages", + "google.ads.admanager_v1.types.dai_session_service", "google.ads.admanager_v1.types.deal_buyer_permission_type_enum", "google.ads.admanager_v1.types.deal_priority_tier_enum", "google.ads.admanager_v1.types.delivery_enums", @@ -348,6 +352,7 @@ from .services.custom_targeting_value_service import CustomTargetingValueServiceClient from .services.dai_authentication_key_service import DaiAuthenticationKeyServiceClient from .services.dai_encoding_profile_service import DaiEncodingProfileServiceClient +from .services.dai_session_service import DaiSessionServiceClient from .services.device_capability_service import DeviceCapabilityServiceClient from .services.device_category_service import DeviceCategoryServiceClient from .services.device_manufacturer_service import DeviceManufacturerServiceClient @@ -844,6 +849,23 @@ ListDaiEncodingProfilesResponse, UpdateDaiEncodingProfileRequest, ) +from .types.dai_session_enums import ( + AdBreakFindingTypeEnum, + AdRequestFindingTypeEnum, + AdResponseTypeEnum, + BreakTypeEnum, + CreativeFindingTypeEnum, + CreativeIdTypeEnum, + PodFindingTypeEnum, + PrefetchStageTypeEnum, + ReportingTypeEnum, + SessionFindingSeverityEnum, + SlateFindingTypeEnum, + StitchingTypeEnum, + TrackingPingFindingTypeEnum, +) +from .types.dai_session_messages import DaiSession +from .types.dai_session_service import GetDaiSessionRequest from .types.deal_buyer_permission_type_enum import DealBuyerPermissionTypeEnum from .types.deal_priority_tier_enum import DealPriorityTierEnum from .types.delivery_enums import ( @@ -1343,12 +1365,15 @@ "ActivateDaiEncodingProfileRequest", "AdBreak", "AdBreakFillTypeEnum", + "AdBreakFindingTypeEnum", "AdBreakMarkupTypeEnum", "AdBreakOptimizationTypeEnum", "AdBreakServiceClient", "AdBreakStateEnum", "AdManagerError", "AdMediaDeliveryConfig", + "AdRequestFindingTypeEnum", + "AdResponseTypeEnum", "AdReviewCenterAd", "AdReviewCenterAdServiceClient", "AdReviewCenterAdStatusEnum", @@ -1654,6 +1679,7 @@ "BreakTemplate", "BreakTemplateMember", "BreakTemplateServiceClient", + "BreakTypeEnum", "Browser", "BrowserLanguage", "BrowserLanguageServiceClient", @@ -1734,6 +1760,8 @@ "CreateTeamRequest", "CreateViewabilityProviderRequest", "Creative", + "CreativeFindingTypeEnum", + "CreativeIdTypeEnum", "CreativePlaceholder", "CreativePlaceholderCompanion", "CreativeRotationTypeEnum", @@ -1785,6 +1813,8 @@ "DaiIngestError", "DaiIngestErrorReasonEnum", "DaiIngestStatusEnum", + "DaiSession", + "DaiSessionServiceClient", "DashBridge", "DataSegmentTargeting", "DeactivateCustomTargetingValueRequest", @@ -1852,6 +1882,7 @@ "GetCustomTargetingValueRequest", "GetDaiAuthenticationKeyRequest", "GetDaiEncodingProfileRequest", + "GetDaiSessionRequest", "GetDefaultThirdPartyDataDeclarationRequest", "GetDeviceCapabilityRequest", "GetDeviceCategoryRequest", @@ -2079,7 +2110,9 @@ "Placement", "PlacementServiceClient", "PlacementStatusEnum", + "PodFindingTypeEnum", "PrefetchSettings", + "PrefetchStageTypeEnum", "PrerollSettings", "PrivateAuction", "PrivateAuctionDeal", @@ -2098,6 +2131,7 @@ "ReportServiceClient", "ReportValue", "ReportVisibilityEnum", + "ReportingTypeEnum", "RequestFormatTargeting", "RequestPlatformEnum", "RequestPlatformTargeting", @@ -2114,6 +2148,7 @@ "ScheduleOptions", "SearchAdReviewCenterAdsRequest", "SearchAdReviewCenterAdsResponse", + "SessionFindingSeverityEnum", "Site", "SiteApprovalStatusEnum", "SiteDisapprovalReasonEnum", @@ -2122,10 +2157,12 @@ "SizeTypeEnum", "SkippableAdTypeEnum", "Slate", + "SlateFindingTypeEnum", "SlateServiceClient", "SlateStatusEnum", "SmartSizeModeEnum", "SourceContentConfig", + "StitchingTypeEnum", "SuggestedAdUnit", "SuggestedAdUnitServiceClient", "TargetPlatformEnum", @@ -2151,6 +2188,7 @@ "ThirdPartyDataDeclarationTypeEnum", "ThirdPartyMeasurementSettings", "TimeUnitEnum", + "TrackingPingFindingTypeEnum", "UnitTypeEnum", "UpdateAdBreakRequest", "UpdateAdRuleRequest", diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json index 3b4410c7b93c..efda67c99567 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json +++ b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json @@ -1067,6 +1067,20 @@ } } }, + "DaiSessionService": { + "clients": { + "rest": { + "libraryClient": "DaiSessionServiceClient", + "rpcs": { + "GetDaiSession": { + "methods": [ + "get_dai_session" + ] + } + } + } + } + }, "DeviceCapabilityService": { "clients": { "rest": { diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py index a59dfd670715..0f411675b722 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.4" # {x-release-please-version} +__version__ = "0.10.5" # {x-release-please-version} diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/__init__.py new file mode 100644 index 000000000000..c4ece0f32e53 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DaiSessionServiceClient + +__all__ = ("DaiSessionServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/client.py new file mode 100644 index 000000000000..9b5b0218e6a5 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/client.py @@ -0,0 +1,893 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version +from google.ads.admanager_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.ads.admanager_v1.types import dai_session_messages, dai_session_service + +from .transports.base import DEFAULT_CLIENT_INFO, DaiSessionServiceTransport +from .transports.rest import DaiSessionServiceRestTransport + + +class DaiSessionServiceClientMeta(type): + """Metaclass for the DaiSessionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[DaiSessionServiceTransport]] + _transport_registry["rest"] = DaiSessionServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[DaiSessionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DaiSessionServiceClient(metaclass=DaiSessionServiceClientMeta): + """Provides methods for handling ``DaiSession`` objects.""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "admanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "admanager.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DaiSessionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DaiSessionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DaiSessionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DaiSessionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def content_path( + network_code: str, + content: str, + ) -> str: + """Returns a fully-qualified content string.""" + return "networks/{network_code}/content/{content}".format( + network_code=network_code, + content=content, + ) + + @staticmethod + def parse_content_path(path: str) -> Dict[str, str]: + """Parses a content path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/content/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def dai_session_path( + network_code: str, + dai_session: str, + ) -> str: + """Returns a fully-qualified dai_session string.""" + return "networks/{network_code}/daiSessions/{dai_session}".format( + network_code=network_code, + dai_session=dai_session, + ) + + @staticmethod + def parse_dai_session_path(path: str) -> Dict[str, str]: + """Parses a dai_session path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/daiSessions/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def live_stream_path( + network_code: str, + live_stream: str, + ) -> str: + """Returns a fully-qualified live_stream string.""" + return "networks/{network_code}/liveStreams/{live_stream}".format( + network_code=network_code, + live_stream=live_stream, + ) + + @staticmethod + def parse_live_stream_path(path: str) -> Dict[str, str]: + """Parses a live_stream path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/liveStreams/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + DaiSessionServiceTransport, + Callable[..., DaiSessionServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dai session service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,DaiSessionServiceTransport,Callable[..., DaiSessionServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DaiSessionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = DaiSessionServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=DaiSessionServiceClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, DaiSessionServiceTransport) + if transport_provided: + # transport is a DaiSessionServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(DaiSessionServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=DaiSessionServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=DaiSessionServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=DaiSessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[DaiSessionServiceTransport], + Callable[..., DaiSessionServiceTransport], + ] = ( + DaiSessionServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DaiSessionServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ads.admanager_v1.DaiSessionServiceClient`.", + extra={ + "serviceName": "google.ads.admanager.v1.DaiSessionService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ads.admanager.v1.DaiSessionService", + "credentialsType": None, + }, + ) + + def get_dai_session( + self, + request: Optional[Union[dai_session_service.GetDaiSessionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dai_session_messages.DaiSession: + r"""Retrieves a ``DaiSession`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_get_dai_session(): + # Create a client + client = admanager_v1.DaiSessionServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetDaiSessionRequest( + name="name_value", + ) + + # Make the request + response = client.get_dai_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.GetDaiSessionRequest, dict]): + The request object. Request object for ``GetDaiSession`` method. + name (str): + Required. The resource name of the DaiSession. The + dai_session can be either the session ID or debug key, + that DAI returns on stream create. For details, see + `Locate a DAI session ID or debug + key `__. + + Format: + ``networks/{network_code}/daiSessions/{dai_session}`` + Format: + ``networks/{network_code}/daiSessions/{session_id}`` + Format: + ``networks/{network_code}/daiSessions/{debug_key}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.DaiSession: + Representation of an individual Dynamic Ad Insertion (DAI) session watching a + [LiveStream][google.ads.admanager.v1.LiveStream] + resource or VOD + [Content][google.ads.admanager.v1.Content] resource. + Use the Stream Activity Monitor (SAM) on the Google + Ad Manager UI to look up this session. For details, + see [Locate a DAI session ID or debug + key](https://support.google.com/admanager/answer/7257678). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dai_session_service.GetDaiSessionRequest): + request = dai_session_service.GetDaiSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_dai_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DaiSessionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("DaiSessionServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/README.rst b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/README.rst new file mode 100644 index 000000000000..e8f175d3df06 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``DaiSessionServiceTransport`` is the ABC for all transports. + +- public child ``DaiSessionServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``DaiSessionServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseDaiSessionServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``DaiSessionServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/__init__.py new file mode 100644 index 000000000000..77ead7d4cc3c --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DaiSessionServiceTransport +from .rest import DaiSessionServiceRestInterceptor, DaiSessionServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DaiSessionServiceTransport]] +_transport_registry["rest"] = DaiSessionServiceRestTransport + +__all__ = ( + "DaiSessionServiceTransport", + "DaiSessionServiceRestTransport", + "DaiSessionServiceRestInterceptor", +) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/base.py new file mode 100644 index 000000000000..5a9e88040412 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/base.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version +from google.ads.admanager_v1.types import dai_session_messages, dai_session_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DaiSessionServiceTransport(abc.ABC): + """Abstract transport class for DaiSessionService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ) + + DEFAULT_HOST: str = "admanager.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_dai_session: gapic_v1.method.wrap_method( + self.get_dai_session, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_dai_session( + self, + ) -> Callable[ + [dai_session_service.GetDaiSessionRequest], + Union[ + dai_session_messages.DaiSession, Awaitable[dai_session_messages.DaiSession] + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("DaiSessionServiceTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/rest.py new file mode 100644 index 000000000000..67c60558fda7 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/rest.py @@ -0,0 +1,707 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ads.admanager_v1._compat import transcode_request +from google.ads.admanager_v1.types import dai_session_messages, dai_session_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseDaiSessionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DaiSessionServiceRestInterceptor: + """Interceptor for DaiSessionService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the DaiSessionServiceRestTransport. + + .. code-block:: python + class MyCustomDaiSessionServiceInterceptor(DaiSessionServiceRestInterceptor): + def pre_get_dai_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_dai_session(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DaiSessionServiceRestTransport(interceptor=MyCustomDaiSessionServiceInterceptor()) + client = DaiSessionServiceClient(transport=transport) + + + """ + + def pre_get_dai_session( + self, + request: dai_session_service.GetDaiSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dai_session_service.GetDaiSessionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_dai_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the DaiSessionService server. + """ + return request, metadata + + def post_get_dai_session( + self, response: dai_session_messages.DaiSession + ) -> dai_session_messages.DaiSession: + """Post-rpc interceptor for get_dai_session + + DEPRECATED. Please use the `post_get_dai_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DaiSessionService server but before + it is returned to user code. This `post_get_dai_session` interceptor runs + before the `post_get_dai_session_with_metadata` interceptor. + """ + return response + + def post_get_dai_session_with_metadata( + self, + response: dai_session_messages.DaiSession, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dai_session_messages.DaiSession, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_dai_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DaiSessionService server but before it is returned to user code. + + We recommend only using this `post_get_dai_session_with_metadata` + interceptor in new development instead of the `post_get_dai_session` interceptor. + When both interceptors are used, this `post_get_dai_session_with_metadata` interceptor runs after the + `post_get_dai_session` interceptor. The (possibly modified) response returned by + `post_get_dai_session` will be passed to + `post_get_dai_session_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DaiSessionService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the DaiSessionService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DaiSessionService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the DaiSessionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DaiSessionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DaiSessionServiceRestInterceptor + + +class DaiSessionServiceRestTransport(_BaseDaiSessionServiceRestTransport): + """REST backend synchronous transport for DaiSessionService. + + Provides methods for handling ``DaiSession`` objects. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[DaiSessionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[DaiSessionServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DaiSessionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetDaiSession( + _BaseDaiSessionServiceRestTransport._BaseGetDaiSession, + DaiSessionServiceRestStub, + ): + def __hash__(self): + return hash("DaiSessionServiceRestTransport.GetDaiSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dai_session_service.GetDaiSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dai_session_messages.DaiSession: + r"""Call the get dai session method over HTTP. + + Args: + request (~.dai_session_service.GetDaiSessionRequest): + The request object. Request object for ``GetDaiSession`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dai_session_messages.DaiSession: + Representation of an individual Dynamic Ad Insertion + (DAI) session watching a + [LiveStream][google.ads.admanager.v1.LiveStream] + resource or VOD + [Content][google.ads.admanager.v1.Content] resource. Use + the Stream Activity Monitor (SAM) on the Google Ad + Manager UI to look up this session. For details, see + `Locate a DAI session ID or debug + key `__. + + """ + + http_options = _BaseDaiSessionServiceRestTransport._BaseGetDaiSession._get_http_options() + request, metadata = self._interceptor.pre_get_dai_session(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDaiSessionServiceRestTransport._BaseGetDaiSession, + "_BaseGetDaiSession__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.DaiSessionServiceClient.GetDaiSession", + extra={ + "serviceName": "google.ads.admanager.v1.DaiSessionService", + "rpcName": "GetDaiSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DaiSessionServiceRestTransport._GetDaiSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dai_session_messages.DaiSession() + pb_resp = dai_session_messages.DaiSession.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_dai_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_dai_session_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dai_session_messages.DaiSession.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.DaiSessionServiceClient.get_dai_session", + extra={ + "serviceName": "google.ads.admanager.v1.DaiSessionService", + "rpcName": "GetDaiSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_dai_session( + self, + ) -> Callable[ + [dai_session_service.GetDaiSessionRequest], dai_session_messages.DaiSession + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDaiSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseDaiSessionServiceRestTransport._BaseCancelOperation, + DaiSessionServiceRestStub, + ): + def __hash__(self): + return hash("DaiSessionServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseDaiSessionServiceRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDaiSessionServiceRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.DaiSessionServiceClient.CancelOperation", + extra={ + "serviceName": "google.ads.admanager.v1.DaiSessionService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DaiSessionServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseDaiSessionServiceRestTransport._BaseGetOperation, DaiSessionServiceRestStub + ): + def __hash__(self): + return hash("DaiSessionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseDaiSessionServiceRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDaiSessionServiceRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.DaiSessionServiceClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.DaiSessionService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DaiSessionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.DaiSessionServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.DaiSessionService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DaiSessionServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/rest_base.py new file mode 100644 index 000000000000..37881bdd3b02 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/dai_session_service/transports/rest_base.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.ads.admanager_v1.types import dai_session_messages, dai_session_service + +from .base import DEFAULT_CLIENT_INFO, DaiSessionServiceTransport + + +class _BaseDaiSessionServiceRestTransport(DaiSessionServiceTransport): + """Base REST backend transport for DaiSessionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGetDaiSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/daiSessions/*}", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}:cancel", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}", + }, + ] + return http_options + + +__all__ = ("_BaseDaiSessionServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py index 7336626e4515..47ae058ac240 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py @@ -586,6 +586,27 @@ ListDaiEncodingProfilesResponse, UpdateDaiEncodingProfileRequest, ) +from .dai_session_enums import ( + AdBreakFindingTypeEnum, + AdRequestFindingTypeEnum, + AdResponseTypeEnum, + BreakTypeEnum, + CreativeFindingTypeEnum, + CreativeIdTypeEnum, + PodFindingTypeEnum, + PrefetchStageTypeEnum, + ReportingTypeEnum, + SessionFindingSeverityEnum, + SlateFindingTypeEnum, + StitchingTypeEnum, + TrackingPingFindingTypeEnum, +) +from .dai_session_messages import ( + DaiSession, +) +from .dai_session_service import ( + GetDaiSessionRequest, +) from .deal_buyer_permission_type_enum import ( DealBuyerPermissionTypeEnum, ) @@ -1647,6 +1668,21 @@ "ListDaiEncodingProfilesRequest", "ListDaiEncodingProfilesResponse", "UpdateDaiEncodingProfileRequest", + "AdBreakFindingTypeEnum", + "AdRequestFindingTypeEnum", + "AdResponseTypeEnum", + "BreakTypeEnum", + "CreativeFindingTypeEnum", + "CreativeIdTypeEnum", + "PodFindingTypeEnum", + "PrefetchStageTypeEnum", + "ReportingTypeEnum", + "SessionFindingSeverityEnum", + "SlateFindingTypeEnum", + "StitchingTypeEnum", + "TrackingPingFindingTypeEnum", + "DaiSession", + "GetDaiSessionRequest", "DealBuyerPermissionTypeEnum", "DealPriorityTierEnum", "CompanionDeliveryOptionEnum", diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_enums.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_enums.py new file mode 100644 index 000000000000..78d39b0c732a --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_enums.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.ads.admanager.v1", + manifest={ + "StitchingTypeEnum", + "ReportingTypeEnum", + "AdResponseTypeEnum", + "BreakTypeEnum", + "PrefetchStageTypeEnum", + "CreativeIdTypeEnum", + "SessionFindingSeverityEnum", + "PodFindingTypeEnum", + "SlateFindingTypeEnum", + "AdBreakFindingTypeEnum", + "TrackingPingFindingTypeEnum", + "CreativeFindingTypeEnum", + "AdRequestFindingTypeEnum", + }, +) + + +class StitchingTypeEnum(proto.Message): + r"""Wrapper message for + [StitchingType][google.ads.admanager.v1.StitchingTypeEnum.StitchingType] + + """ + + class StitchingType(proto.Enum): + r"""Indicates how ads are stitched into the session. + + Values: + STITCHING_TYPE_UNSPECIFIED (0): + Default value. + STITCHED (1): + DAI stitches ad pods into the session. + POD_SERVING (2): + Ready to stitch ad pods are provided by DAI + and stitched by the publisher. + """ + + STITCHING_TYPE_UNSPECIFIED = 0 + STITCHED = 1 + POD_SERVING = 2 + + +class ReportingTypeEnum(proto.Message): + r"""Wrapper message for + [ReportingType][google.ads.admanager.v1.ReportingTypeEnum.ReportingType] + + """ + + class ReportingType(proto.Enum): + r"""Indicates how ad tracking URLs are reported for the session. + + Values: + REPORTING_TYPE_UNSPECIFIED (0): + Default value. + CLIENT (1): + Tracking URLs are pinged on client side. + SERVER (2): + Tracking URLs are pinged on server side. + CLIENT_INITIATED_SERVER_TRIGGERED (3): + Tracking URLs are pinged on server side upon + receiving ad media verification requests from + client. + """ + + REPORTING_TYPE_UNSPECIFIED = 0 + CLIENT = 1 + SERVER = 2 + CLIENT_INITIATED_SERVER_TRIGGERED = 3 + + +class AdResponseTypeEnum(proto.Message): + r"""Wrapper message for + [AdResponseType][google.ads.admanager.v1.AdResponseTypeEnum.AdResponseType] + + """ + + class AdResponseType(proto.Enum): + r"""The type of the ad response. + + Values: + AD_RESPONSE_TYPE_UNSPECIFIED (0): + Default value. + VAST (1): + The ad response is VAST (Video Ad Serving + Template). + VMAP (2): + The ad response is VMAP (Video Multiple Ad + Playlist). + """ + + AD_RESPONSE_TYPE_UNSPECIFIED = 0 + VAST = 1 + VMAP = 2 + + +class BreakTypeEnum(proto.Message): + r"""Wrapper message for + [BreakType][google.ads.admanager.v1.BreakTypeEnum.BreakType] + + """ + + class BreakType(proto.Enum): + r"""Different break types that DAI supports for ad insertion. + + Values: + BREAK_TYPE_UNSPECIFIED (0): + Default value. + PREROLL (1): + Before content. + MIDROLL (2): + In the middle of content. + POSTROLL (3): + After content. + AUXILIARY (4): + Non-linear auxiliary ads run concurrently + with the content (e.g., Pause Ads). + """ + + BREAK_TYPE_UNSPECIFIED = 0 + PREROLL = 1 + MIDROLL = 2 + POSTROLL = 3 + AUXILIARY = 4 + + +class PrefetchStageTypeEnum(proto.Message): + r"""Wrapper message for + [PrefetchStageType][google.ads.admanager.v1.PrefetchStageTypeEnum.PrefetchStageType] + + """ + + class PrefetchStageType(proto.Enum): + r"""Indicates the prefetch stage for an ad pod. + + Values: + PREFETCH_STAGE_TYPE_UNSPECIFIED (0): + Default value. + ONE (1): + Prefetch stage 1. + TWO (2): + Prefetch stage 2. + DISABLED (3): + Prefetch is disabled for this ad pod. + """ + + PREFETCH_STAGE_TYPE_UNSPECIFIED = 0 + ONE = 1 + TWO = 2 + DISABLED = 3 + + +class CreativeIdTypeEnum(proto.Message): + r"""Wrapper message for + [CreativeIdType][google.ads.admanager.v1.CreativeIdTypeEnum.CreativeIdType] + + """ + + class CreativeIdType(proto.Enum): + r"""The ID types in a VAST response to uniquely identify a + creative. + + Values: + CREATIVE_ID_TYPE_UNSPECIFIED (0): + Default value. + AD_ID (1): + An ad server-defined ID string for the ad. + CREATIVE_ID (2): + An ad server-defined ID for the creative. + CREATIVE_AD_ID (3): + Identifies the ad with which the creative is + served. This is an optional attribute of + Creative element in the VAST specification. + MEDIA_URI_HASH (4): + A media URI was used to generate a hash + value, hopefully unique to this creative. + UNIVERSAL_AD_ID (5): + Universal Ad ID of the creative as defined in the VAST 4.0 + spec: + http://www.iab.com/wp-content/uploads/2016/04/VAST4.0_Updated_April_2016.pdf + Section 3.7.1 The ID string format is "\|". + MEDIA_URI_PATH (6): + ID value is the path of the URL of the + highest bitrate mediafile found in the response. + CREATIVE_AD_ID_WITH_FALLBACK (8): + ID value is the VAST/Ad/Inline/Creative ``adId`` attribute. + If absent, the value will fallback to the + VAST/Ad/Inline/Creative ``id`` attribute. If that is also + absent, the value will again fallback to the VAST/Ad ``id`` + attribute. + MEDIA_URI (9): + ID value is the URL of the highest bitrate + mediafile found in the response. + CANONICALIZED_MEDIA_URI (11): + ID value is a projection of the URL of the + highest bitrate mediafile found in the response. + GOOGLE_VIDEO_REGISTRY_ID (10): + ID value is the Google Video Registry ID. + """ + + CREATIVE_ID_TYPE_UNSPECIFIED = 0 + AD_ID = 1 + CREATIVE_ID = 2 + CREATIVE_AD_ID = 3 + MEDIA_URI_HASH = 4 + UNIVERSAL_AD_ID = 5 + MEDIA_URI_PATH = 6 + CREATIVE_AD_ID_WITH_FALLBACK = 8 + MEDIA_URI = 9 + CANONICALIZED_MEDIA_URI = 11 + GOOGLE_VIDEO_REGISTRY_ID = 10 + + +class SessionFindingSeverityEnum(proto.Message): + r"""Wrapper message for + [SessionFindingSeverity][google.ads.admanager.v1.SessionFindingSeverityEnum.SessionFindingSeverity] + + """ + + class SessionFindingSeverity(proto.Enum): + r"""Severity levels for a finding. + + Values: + SESSION_FINDING_SEVERITY_UNSPECIFIED (0): + Default value. + INFO (1): + The finding is informational. + WARNING (2): + The finding is a warning. + ERROR (3): + The finding is an error. + """ + + SESSION_FINDING_SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + + +class PodFindingTypeEnum(proto.Message): + r"""Wrapper message for + [PodFindingType][google.ads.admanager.v1.PodFindingTypeEnum.PodFindingType] + + """ + + class PodFindingType(proto.Enum): + r"""Types of findings that can occur while decisioning an ad pod. + + Values: + POD_FINDING_TYPE_UNSPECIFIED (0): + Default value. + INTERNAL_ERROR (1): + Internal DAI error. + AD_POD_DROPPED_EMPTY_ADS (2): + Ad pod doesn't contain ad(s) available for + insertion. + AD_POD_DROPPED_INCOMPATIBLE_TIMEOFFSET (3): + Ad pod was dropped because the request is + incompatible with the time offset returned by + the VMAP. + AD_POD_DROPPED_UNSUPPORTED_TYPE (4): + Ad pod was dropped because it was an + unsupported type for this session. + """ + + POD_FINDING_TYPE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + AD_POD_DROPPED_EMPTY_ADS = 2 + AD_POD_DROPPED_INCOMPATIBLE_TIMEOFFSET = 3 + AD_POD_DROPPED_UNSUPPORTED_TYPE = 4 + + +class SlateFindingTypeEnum(proto.Message): + r"""Wrapper message for + [SlateFindingType][google.ads.admanager.v1.SlateFindingTypeEnum.SlateFindingType] + + """ + + class SlateFindingType(proto.Enum): + r"""A finding that occurred regarding the slate creative. + + Values: + SLATE_FINDING_TYPE_UNSPECIFIED (0): + Default value. + INTERNAL_ERROR (1): + Internal DAI error. + SLATE_STATUS_SKIPPED (2): + Slate was skipped for this ad break and + underlying content was stitched instead because + slate was disabled for underfill or empty break. + SLATE_STATUS_DROPPED_UNKNOWN (3): + Slate was not inserted into this ad break due + to an unknown reason. + SLATE_STATUS_MINIMUM_INSERTED (4): + The minimum amount of slate was inserted into + an underfilled ad break to cover the gap between + the end of the ads and the next segment start of + the trimmed underlying linear content. + """ + + SLATE_FINDING_TYPE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + SLATE_STATUS_SKIPPED = 2 + SLATE_STATUS_DROPPED_UNKNOWN = 3 + SLATE_STATUS_MINIMUM_INSERTED = 4 + + +class AdBreakFindingTypeEnum(proto.Message): + r"""Wrapper message for + [AdBreakFindingType][google.ads.admanager.v1.AdBreakFindingTypeEnum.AdBreakFindingType] + + """ + + class AdBreakFindingType(proto.Enum): + r"""A finding that occurred while serving an ad break for a + session. + + Values: + AD_BREAK_FINDING_TYPE_UNSPECIFIED (0): + Default value. + INTERNAL_ERROR (1): + Internal DAI error. + AD_POD_DROPPED_TOO_MANY_AD_PODS (2): + Ad pod was dropped, the number of ad breaks + is less than the number of decisioned ad pods. + EXCEEDS_MAX_FILLER (3): + Ad pod doesn't contain enough ads - requires + more filler than specified. + ADS_STATUS_DROPPED_FOR_PREROLL (4): + The midroll ad break was skipped due to + overlapping with preroll. + ADS_STATUS_ALL_ADS_MISSING_ASSETS (5): + Ad pod was dropped due to all of the ads in + the pod missing their assets, probably due to + the assets not yet being transcoded. + ADS_STATUS_OUT_OF_WINDOW (6): + Ad pod is outside of the window at session + creation time so ad pod was skipped and + underlying content was stitched instead. + ADS_STATUS_DISABLED (7): + Ads are disabled for this session. + ADS_STATUS_STORAGE_ERROR (8): + Decisioned ad pod couldn't be fetched from + storage. + ADS_STATUS_EXPIRED (9): + Ad pod expired because the ad request + couldn't finish before the deadline. + ADS_STATUS_HOLIDAY (10): + Ad pod occurred within the configured ad + holiday. + ADS_STATUS_DROPPED_SLATE_UNAVAILABLE (11): + Ad pod was dropped because slate was + unavailable and underlying content was stitched + instead. + ADS_STATUS_NO_ADS_AVAILABLE_BEFORE_DEADLINE (12): + Ad pod was dropped because there were no ads + available before the deadline. + ADS_STATUS_INVALID_POD_REQUEST (13): + Ad pod was dropped due to an invalid pod + request. + ADS_STATUS_DROPPED_FOR_MIDROLL (14): + The requested pre-roll break would overlap + with a mid-roll ad break. + ADS_STATUS_DROPPED_BREAK_DURATION_TOO_SHORT (15): + The duration of the ad break was too short to + request ads. + ADS_STATUS_DROPPED_STREAM_CREATED_AFTER_BREAK (16): + Session created after the ad break ended. + ADS_STATUS_DROPPED_MEDIA_ANALYSIS_UNAVAILABLE (17): + Information about the content stream that is + required to stitch the ads is missing or + unavailable. + ADS_STATUS_UNKNOWN (18): + The serving or insertion status of the ad + break is unknown. + UNSERVED_BREAK (19): + Ad break was not served. + PREROLL_AUDIO_VIDEO_MISALIGNMENT (20): + The content segment boundary at the end of + the preroll has misaligned video and audio + segments. + """ + + AD_BREAK_FINDING_TYPE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + AD_POD_DROPPED_TOO_MANY_AD_PODS = 2 + EXCEEDS_MAX_FILLER = 3 + ADS_STATUS_DROPPED_FOR_PREROLL = 4 + ADS_STATUS_ALL_ADS_MISSING_ASSETS = 5 + ADS_STATUS_OUT_OF_WINDOW = 6 + ADS_STATUS_DISABLED = 7 + ADS_STATUS_STORAGE_ERROR = 8 + ADS_STATUS_EXPIRED = 9 + ADS_STATUS_HOLIDAY = 10 + ADS_STATUS_DROPPED_SLATE_UNAVAILABLE = 11 + ADS_STATUS_NO_ADS_AVAILABLE_BEFORE_DEADLINE = 12 + ADS_STATUS_INVALID_POD_REQUEST = 13 + ADS_STATUS_DROPPED_FOR_MIDROLL = 14 + ADS_STATUS_DROPPED_BREAK_DURATION_TOO_SHORT = 15 + ADS_STATUS_DROPPED_STREAM_CREATED_AFTER_BREAK = 16 + ADS_STATUS_DROPPED_MEDIA_ANALYSIS_UNAVAILABLE = 17 + ADS_STATUS_UNKNOWN = 18 + UNSERVED_BREAK = 19 + PREROLL_AUDIO_VIDEO_MISALIGNMENT = 20 + + +class TrackingPingFindingTypeEnum(proto.Message): + r"""Wrapper message for + [TrackingPingFindingType][google.ads.admanager.v1.TrackingPingFindingTypeEnum.TrackingPingFindingType] + + """ + + class TrackingPingFindingType(proto.Enum): + r"""A finding that occurred while pinging tracking URLs for a + session. + + Values: + TRACKING_PING_FINDING_TYPE_UNSPECIFIED (0): + Default value. + INTERNAL_ERROR (1): + Internal DAI error. + FAILED_PING (2): + Failed to ping a URL. + """ + + TRACKING_PING_FINDING_TYPE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + FAILED_PING = 2 + + +class CreativeFindingTypeEnum(proto.Message): + r"""Wrapper message for + [CreativeFindingType][google.ads.admanager.v1.CreativeFindingTypeEnum.CreativeFindingType] + + """ + + class CreativeFindingType(proto.Enum): + r"""A finding that occurred while looking up creative + information. + + Values: + CREATIVE_FINDING_TYPE_UNSPECIFIED (0): + Default value. + UNIDENTIFIED_AD_CREATIVE (1): + Ad was dropped because the VAST document + returned did not contain enough information to + successfully identify the creative media. + UNKNOWN_AD_CREATIVE (2): + Ad was dropped because the system has no + knowledge of the creative media to insert into + the DAI session. Creative will be reactively + loaded into the system for subsequent use. + AD_CREATIVE_LOOKUP_FAILED (3): + Error occurred when performing lookup on the + ad creative for insertion into the DAI session. + DISABLED_AD_CREATIVE (4): + Creative has been disabled from serving. + FAILED_AD_CREATIVE (5): + Ad creative is known but failed to acquire / + transcode for serving. + AD_CREATIVE_ENCODING_MATCH_FAILURE (6): + Ad creative does not have suitable encodings + available to be successfully stitched into a DAI + session. + MISMATCHED_FRAME_COUNT (7): + Incorrect number of frames available for + creative when exact frame count is required for + a specific duration. + MISSING_TRANSCODES (8): + Ad creative doesn't have any encodings + available. + AD_DROPPED_TO_FIT_BREAK (9): + Ad creative is dropped due to pod trimming to + fit the break. + """ + + CREATIVE_FINDING_TYPE_UNSPECIFIED = 0 + UNIDENTIFIED_AD_CREATIVE = 1 + UNKNOWN_AD_CREATIVE = 2 + AD_CREATIVE_LOOKUP_FAILED = 3 + DISABLED_AD_CREATIVE = 4 + FAILED_AD_CREATIVE = 5 + AD_CREATIVE_ENCODING_MATCH_FAILURE = 6 + MISMATCHED_FRAME_COUNT = 7 + MISSING_TRANSCODES = 8 + AD_DROPPED_TO_FIT_BREAK = 9 + + +class AdRequestFindingTypeEnum(proto.Message): + r"""Wrapper message for + [AdRequestFindingType][google.ads.admanager.v1.AdRequestFindingTypeEnum.AdRequestFindingType] + + """ + + class AdRequestFindingType(proto.Enum): + r"""A finding that occurred while making an ad request. + + Values: + AD_REQUEST_FINDING_TYPE_UNSPECIFIED (0): + Default value. + INTERNAL_ERROR (1): + Internal DAI error. + AD_REQUEST_ERROR (2): + An error while making an ad request. + VAST_PARSE_ERROR (3): + Generic VAST parsing error. + UNSUPPORTED_AD_SYSTEM (4): + AdSystem reported in VAST is not supported. + CANNOT_FIND_UNIQUE_TRANSCODE_ID (5): + Ad element does not contain enough + information to generate a unique transcode ID. + MISSING_INLINE_ELEMENTS (7): + No InLine elements found in the Ad. + MAX_WRAPPER_DEPTH_REACHED (8): + Reached the maximum number of VAST redirects. + AD_TAG_PARSE_ERROR (9): + Error while parsing ad tag. + VMAP_PARSE_ERROR (10): + Generic VMAP parsing error. + INVALID_VMAP_RESPONSE (11): + Invalid VMAP data (Able to parse VMAP but XML + attributes have invalid data). + NO_AD_BREAKS_IN_VMAP (12): + VMAP response contains no ad breaks. + CUSTOM_AD_SOURCE_IN_VMAP (13): + VMAP contains custom ad source which is not + supported. + AD_BREAK_TYPE_NOT_SUPPORTED (14): + VMAP contains an adbreak that is not + supported. + NEITHER_AD_SOURCE_NOR_TRACKING (15): + VMAP contains an adbreak that has neither ad + source nor tracking events. + SKIPPABLE_AD_NOT_SUPPORTED (16): + Client doesn't support skippable ads. The ad + was a skippable ad. + AD_REQUEST_TIMEOUT (17): + The request has timed out. + DUPLICATE_AD_TAG (18): + The same ad tag was already used in the same + pod. + FOLLOW_REDIRECTS_IS_FALSE (19): + VMAP AdSource followRedirects is set as + false. + UNSUPPORTED_VAST_VERSION (20): + VAST version is not supported. + NO_VALID_MEDIAFILES_FOUND (21): + No media files were found in the VAST ad. + """ + + AD_REQUEST_FINDING_TYPE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + AD_REQUEST_ERROR = 2 + VAST_PARSE_ERROR = 3 + UNSUPPORTED_AD_SYSTEM = 4 + CANNOT_FIND_UNIQUE_TRANSCODE_ID = 5 + MISSING_INLINE_ELEMENTS = 7 + MAX_WRAPPER_DEPTH_REACHED = 8 + AD_TAG_PARSE_ERROR = 9 + VMAP_PARSE_ERROR = 10 + INVALID_VMAP_RESPONSE = 11 + NO_AD_BREAKS_IN_VMAP = 12 + CUSTOM_AD_SOURCE_IN_VMAP = 13 + AD_BREAK_TYPE_NOT_SUPPORTED = 14 + NEITHER_AD_SOURCE_NOR_TRACKING = 15 + SKIPPABLE_AD_NOT_SUPPORTED = 16 + AD_REQUEST_TIMEOUT = 17 + DUPLICATE_AD_TAG = 18 + FOLLOW_REDIRECTS_IS_FALSE = 19 + UNSUPPORTED_VAST_VERSION = 20 + NO_VALID_MEDIAFILES_FOUND = 21 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_messages.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_messages.py new file mode 100644 index 000000000000..48c9e24fb4cf --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_messages.py @@ -0,0 +1,1279 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.ads.admanager_v1.types import dai_session_enums + +__protobuf__ = proto.module( + package="google.ads.admanager.v1", + manifest={ + "DaiSession", + }, +) + + +class DaiSession(proto.Message): + r"""Representation of an individual Dynamic Ad Insertion (DAI) session + watching a [LiveStream][google.ads.admanager.v1.LiveStream] resource + or VOD [Content][google.ads.admanager.v1.Content] resource. Use the + Stream Activity Monitor (SAM) on the Google Ad Manager UI to look up + this session. For details, see `Locate a DAI session ID or debug + key `__. + + Attributes: + name (str): + Identifier. The resource name of the ``DaiSession``. + creation_context (google.ads.admanager_v1.types.DaiSession.CreationContext): + Output only. Context data to create the DAI + session. + slate (google.ads.admanager_v1.types.DaiSession.Creative): + Output only. Slate creative to use in the DAI + session for unfilled ad durations. + ad_selections (MutableMapping[int, google.ads.admanager_v1.types.DaiSession.AdSelection]): + Output only. The ad requests, ad responses + and nested ads in the DAI session. + ad_pods (MutableMapping[int, google.ads.admanager_v1.types.DaiSession.AdPod]): + Output only. All decisioned ad pods for this + session, disregarding serving status. Keyed by a + unique ID to reference an ad pod from a + different submessage. + ad_breaks (MutableMapping[int, google.ads.admanager_v1.types.DaiSession.AdBreak]): + Output only. All DAI ad breaks for this + session. Contains information such as ad + duration, slate duration, and various ad + statuses. Keyed by a unique ID to reference an + ad break from a different submessage. + findings (MutableSequence[google.ads.admanager_v1.types.DaiSession.Finding]): + Output only. Information about errors or + notable discoveries that occurred during a + session. + session_duration (google.protobuf.duration_pb2.Duration): + Output only. The duration of the DAI session, + calculated as the difference between the + timestamp of DAI's latest recorded event and the + timestamp of the session create request. + """ + + class CreationContext(proto.Message): + r"""Context data to create the DAI session. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + linear_info (google.ads.admanager_v1.types.DaiSession.CreationContext.LinearInfo): + Output only. The + [LiveStream][google.ads.admanager.v1.LiveStream] resource in + the stream request that creates the DAI session. + + This field is a member of `oneof`_ ``content_info``. + vod_info (google.ads.admanager_v1.types.DaiSession.CreationContext.VodInfo): + Output only. The [Content][google.ads.admanager.v1.Content] + resource in the stream request that creates the DAI session. + + This field is a member of `oneof`_ ``content_info``. + debug_key (str): + Output only. The string the ``dai-sam-id`` parameter sets in + the DAI stream request. For details, see `Locate a DAI + session ID or debug + key `__. + + This field is a member of `oneof`_ ``_debug_key``. + content_title (str): + Output only. The + [LiveStream.display_name][google.ads.admanager.v1.LiveStream.display_name] + field or + [Content.display_name][google.ads.admanager.v1.Content.display_name] + field associated with the DAI session. + + This field is a member of `oneof`_ ``_content_title``. + session_title (str): + Output only. The string the ``session_title`` parameter sets + in the DAI stream request. For details, see + `CreateStreamOptions `__. + + This field is a member of `oneof`_ ``_session_title``. + stream_create_request (google.ads.admanager_v1.types.DaiSession.HttpRequest): + Output only. The HTTP request creating the DAI session. For + details, see `Linear + API `__, + `VOD + API `__, + `pod serving live + API `__ + and `pod serving VOD + API `__. + stitching_type (google.ads.admanager_v1.types.StitchingTypeEnum.StitchingType): + Output only. Whether the stream request is for `Full-service + DAI `__ or + `Pod + serving `__. + + This field is a member of `oneof`_ ``_stitching_type``. + reporting_type (google.ads.admanager_v1.types.ReportingTypeEnum.ReportingType): + Output only. Whether ad tracking URLs are pinged on the + client side or server side. If IMA SDK is used to make the + stream requests, IMA SDK pings the ad tracking URLs on the + client side. For server-side beaconing, see `Integrate with + DAI using server-side beaconing + (SSB) `__. + + This field is a member of `oneof`_ ``_reporting_type``. + interstitial_enabled (bool): + Output only. Whether the parameter ``dai-istl`` on the + stream request is set to true. This parameter is only + accepted for + [LiveStream][google.ads.admanager.v1.LiveStream] resources + with the + [dynamic_ad_insertion_type][google.ads.admanager.v1.LiveStream.dynamic_ad_insertion_type] + field set to + [DynamicAdInsertionType.LINEAR][google.ads.admanager.v1.DynamicAdInsertionTypeEnum.DynamicAdInsertionType.LINEAR] + value. + + This field is a member of `oneof`_ ``_interstitial_enabled``. + """ + + class VodInfo(proto.Message): + r"""The VOD [Content][google.ads.admanager.v1.Content] resource in the + stream request that creates the DAI session. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + content (str): + Output only. The + [name][google.ads.admanager.v1.Content.name] field of the + VOD [Content][google.ads.admanager.v1.Content] resource. + + This field is a member of `oneof`_ ``_content``. + cms_id (int): + Output only. The identifier of the content source from which + Google Ad Manager ingested the + [Content][google.ads.admanager.v1.Content] resource + associated with this session. For more information, see + `Create a content source for video on + demand `__. + + This field is a member of `oneof`_ ``_cms_id``. + vid (str): + Output only. The video ID of the + [Content][google.ads.admanager.v1.Content] resource that + this session is associated with. This value is the same as + the + [CmsContent.cms_content_id][google.ads.admanager.v1.CmsContent.cms_content_id] + field. For details, see `Content ingestion and best + practices `__. + + This field is a member of `oneof`_ ``_vid``. + cue_points (MutableSequence[int]): + Output only. The cue points detected in the + ingested VOD content manifest. Stored in + milliseconds starting from the beginning of the + content. + content_duration (google.protobuf.duration_pb2.Duration): + Output only. The VOD + [Content.duration][google.ads.admanager.v1.Content.duration] + field. Represents the duration of the content without ads. + """ + + content: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + cms_id: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + vid: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + cue_points: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=4, + ) + content_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + class LinearInfo(proto.Message): + r"""The [LiveStream][google.ads.admanager.v1.LiveStream] resource in the + stream request that creates the DAI session. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + live_stream (str): + Output only. The + [name][google.ads.admanager.v1.LiveStream.name] field of the + [LiveStream][google.ads.admanager.v1.LiveStream] resource. + + This field is a member of `oneof`_ ``_live_stream``. + asset_key (str): + Output only. The + [LiveStream.asset_key][google.ads.admanager.v1.LiveStream.asset_key] + field. Google Ad Manager only generates this field for + livestreams with the + [dynamic_ad_insertion_type][google.ads.admanager.v1.LiveStream.dynamic_ad_insertion_type] + field set to + [DynamicAdInsertionType.LINEAR][google.ads.admanager.v1.DynamicAdInsertionTypeEnum.DynamicAdInsertionType.LINEAR] + value. + + This field is a member of `oneof`_ ``_asset_key``. + custom_asset_key (str): + Output only. The + [LiveStream.custom_asset_key][google.ads.admanager.v1.LiveStream.custom_asset_key] + field. This field is only populated for livestreams with the + [dynamic_ad_insertion_type][google.ads.admanager.v1.LiveStream.dynamic_ad_insertion_type] + field set to + [DynamicAdInsertionType.POD_SERVING_MANIFEST][google.ads.admanager.v1.DynamicAdInsertionTypeEnum.DynamicAdInsertionType.POD_SERVING_MANIFEST] + value or + [DynamicAdInsertionType.POD_SERVING_REDIRECT][google.ads.admanager.v1.DynamicAdInsertionTypeEnum.DynamicAdInsertionType.POD_SERVING_REDIRECT] + value. + + This field is a member of `oneof`_ ``_custom_asset_key``. + prefetch_enabled (bool): + Output only. Whether the + [LiveStream.prefetch_enabled][google.ads.admanager.v1.LiveStream.prefetch_enabled] + field is set to true. + + This field is a member of `oneof`_ ``_prefetch_enabled``. + pod_trimming_enabled (bool): + Output only. Whether ad pod trimming is + enabled for the DAI session. + + This field is a member of `oneof`_ ``_pod_trimming_enabled``. + pod_trim_tolerance (google.protobuf.duration_pb2.Duration): + Optional. The maximum duration allowed to be + trimmed from an ad pod before whole ads are + dropped. This field is only populated when pod + trimming is enabled. + + This field is a member of `oneof`_ ``_pod_trim_tolerance``. + event_start_time (google.protobuf.timestamp_pb2.Timestamp): + The + [LiveStream.start_time][google.ads.admanager.v1.LiveStream.start_time] + field. + event_end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The + [LiveStream.end_time][google.ads.admanager.v1.LiveStream.end_time] + field. + """ + + live_stream: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + asset_key: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + custom_asset_key: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + prefetch_enabled: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + pod_trimming_enabled: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + pod_trim_tolerance: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message=duration_pb2.Duration, + ) + event_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + event_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + linear_info: "DaiSession.CreationContext.LinearInfo" = proto.Field( + proto.MESSAGE, + number=2, + oneof="content_info", + message="DaiSession.CreationContext.LinearInfo", + ) + vod_info: "DaiSession.CreationContext.VodInfo" = proto.Field( + proto.MESSAGE, + number=3, + oneof="content_info", + message="DaiSession.CreationContext.VodInfo", + ) + debug_key: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + content_title: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + session_title: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + stream_create_request: "DaiSession.HttpRequest" = proto.Field( + proto.MESSAGE, + number=1, + message="DaiSession.HttpRequest", + ) + stitching_type: dai_session_enums.StitchingTypeEnum.StitchingType = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=dai_session_enums.StitchingTypeEnum.StitchingType, + ) + reporting_type: dai_session_enums.ReportingTypeEnum.ReportingType = proto.Field( + proto.ENUM, + number=5, + optional=True, + enum=dai_session_enums.ReportingTypeEnum.ReportingType, + ) + interstitial_enabled: bool = proto.Field( + proto.BOOL, + number=6, + optional=True, + ) + + class AdSelection(proto.Message): + r"""The ad requests, ad response, and nested ads in the DAI + session. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.ads.admanager_v1.types.AdResponseTypeEnum.AdResponseType): + Output only. Response type of the parent ad + request. + + This field is a member of `oneof`_ ``_type``. + ad_request (google.ads.admanager_v1.types.DaiSession.AdSelection.AdRequest): + Output only. Top-level ad request. + """ + + class AdRequest(proto.Message): + r"""Top-level ad request. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ad_request_key (int): + Output only. Ad request ID. + + This field is a member of `oneof`_ ``_ad_request_key``. + http_request (google.ads.admanager_v1.types.DaiSession.HttpRequest): + Output only. The HTTP request of the ad + request. + child_requests (MutableSequence[google.ads.admanager_v1.types.DaiSession.AdSelection.AdRequest]): + Output only. Ad requests made to follow + redirects or unwrap a previous VMAP or VAST + wrapper ad response. + ad_tag (str): + Output only. The ad request URL. + + This field is a member of `oneof`_ ``_ad_tag``. + effective_ad_request_url (str): + Output only. The effective ad request URL header value on + the ad response. This value is only populated for VMAP ad + requests when video playlist internal redirects are enabled. + For details, see `Internal redirect to Google Campaign + Manager + 360 `__. + + This field is a member of `oneof`_ ``_effective_ad_request_url``. + """ + + ad_request_key: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + http_request: "DaiSession.HttpRequest" = proto.Field( + proto.MESSAGE, + number=2, + message="DaiSession.HttpRequest", + ) + child_requests: MutableSequence["DaiSession.AdSelection.AdRequest"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message="DaiSession.AdSelection.AdRequest", + ) + ) + ad_tag: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + effective_ad_request_url: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + type_: dai_session_enums.AdResponseTypeEnum.AdResponseType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.AdResponseTypeEnum.AdResponseType, + ) + ad_request: "DaiSession.AdSelection.AdRequest" = proto.Field( + proto.MESSAGE, + number=2, + message="DaiSession.AdSelection.AdRequest", + ) + + class AdPod(proto.Message): + r"""Information about a single decisioned ad pod in this session. + This message pertains to the smallest unit of ads to insert in a + session, and might be a pod fragment. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + requested_break_type (google.ads.admanager_v1.types.BreakTypeEnum.BreakType): + Output only. Type of ad break this ad pod was + decisioned for. + + This field is a member of `oneof`_ ``_requested_break_type``. + ad_request_key (int): + Output only. Ad request ID that links to the + ad request that resulted in this ad pod. + + This field is a member of `oneof`_ ``_ad_request_key``. + creatives (MutableMapping[int, google.ads.admanager_v1.types.DaiSession.Creative]): + Output only. The creatives in this ad pod. + Keyed by a unique ID used to reference this + creative from a different submessage. + prefetch_stage (google.ads.admanager_v1.types.PrefetchStageTypeEnum.PrefetchStageType): + Output only. Indicates the prefetch stage for this ad pod. + If prefetch is not enabled this stage is set to the + [PrefetchStageType.DISABLED][google.ads.admanager.v1.PrefetchStageTypeEnum.PrefetchStageType.DISABLED] + value. + + This field is a member of `oneof`_ ``_prefetch_stage``. + ad_break_id (str): + Output only. Publisher-provided or DAI-generated break ID + for the `Ad break + API `__ or + `pod serving + API `__. + + This field is a member of `oneof`_ ``_ad_break_id``. + label (str): + Output only. Descriptive label for this ad + pod, used to distinguish ad pods from one + another in this session. e.g. "midroll-1", "2". + + This field is a member of `oneof`_ ``_label``. + """ + + requested_break_type: dai_session_enums.BreakTypeEnum.BreakType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.BreakTypeEnum.BreakType, + ) + ad_request_key: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + creatives: MutableMapping[int, "DaiSession.Creative"] = proto.MapField( + proto.INT64, + proto.MESSAGE, + number=3, + message="DaiSession.Creative", + ) + prefetch_stage: dai_session_enums.PrefetchStageTypeEnum.PrefetchStageType = ( + proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=dai_session_enums.PrefetchStageTypeEnum.PrefetchStageType, + ) + ) + ad_break_id: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + class AdBreak(proto.Message): + r"""Information about an ad break in this session. Includes + statuses such as ad and slate durations. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + linear (google.ads.admanager_v1.types.DaiSession.AdBreak.LinearBreak): + Output only. Information on the break for a + linear session. + + This field is a member of `oneof`_ ``stream_type_info``. + vod (google.ads.admanager_v1.types.DaiSession.AdBreak.VodBreak): + Output only. Information on the break for a + VOD session. + + This field is a member of `oneof`_ ``stream_type_info``. + pod_keys (MutableSequence[int]): + Output only. Ad pod ID that links to one or + more decisioned ad pods for this break. Most + types of sessions will have a single pod key, + but in the case of prefetched pods there will be + two pod keys. + ad_break_id (str): + Output only. Publisher-provided or DAI-generated break ID + for the `Ad break + API `__ or + `pod serving + API `__. + + This field is a member of `oneof`_ ``_ad_break_id``. + break_type (google.ads.admanager_v1.types.BreakTypeEnum.BreakType): + Output only. Type of break this represents. + + This field is a member of `oneof`_ ``_break_type``. + break_sequence (int): + Output only. The index of this ad break in + the session. + + This field is a member of `oneof`_ ``_break_sequence``. + served_ads_duration (google.protobuf.duration_pb2.Duration): + Output only. The duration of ads that were + inserted for this break. + executed_break_duration (google.protobuf.duration_pb2.Duration): + Output only. The total duration of the break + as it was served by DAI. In VOD, this value is + the duration of ads inserted in between content. + In linear, this value is the duration between + cue out and cue in. + tracking_pings (MutableMapping[int, google.ads.admanager_v1.types.DaiSession.AdBreak.TrackingPing]): + Output only. Tracking pings that were issued + for this break. Keyed by a unique ID to + reference this tracking ping from a different + submessage. + """ + + class VodBreak(proto.Message): + r"""Represents Video on Demand related break information. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Output only. The time difference between the + start of this break and the start of the + session. Includes the time for any preceding ad + breaks. + """ + + time_offset: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + class LinearBreak(proto.Message): + r"""Represents linear session related break information. + + Attributes: + break_start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of when the break + started. + expected_break_duration (google.protobuf.duration_pb2.Duration): + Output only. The duration of the placement + opportunity associated with the break. + slate_duration (google.protobuf.duration_pb2.Duration): + Output only. The duration of slate that was + inserted for this break. + underlying_duration (google.protobuf.duration_pb2.Duration): + Output only. The duration of underlying + content that was inserted for this break. + """ + + break_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + expected_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + slate_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + underlying_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + class TrackingPing(proto.Message): + r"""Information about a tracking ping issued for a break. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + original_tracking_event_id (str): + Output only. A unique ID for this tracking + event, which is the ID3 tag in client-side + reporting. + + This field is a member of `oneof`_ ``_original_tracking_event_id``. + request (google.ads.admanager_v1.types.DaiSession.HttpRequest): + Output only. The HTTP request made to the ad + server for this tracking ping. + """ + + original_tracking_event_id: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + request: "DaiSession.HttpRequest" = proto.Field( + proto.MESSAGE, + number=2, + message="DaiSession.HttpRequest", + ) + + linear: "DaiSession.AdBreak.LinearBreak" = proto.Field( + proto.MESSAGE, + number=7, + oneof="stream_type_info", + message="DaiSession.AdBreak.LinearBreak", + ) + vod: "DaiSession.AdBreak.VodBreak" = proto.Field( + proto.MESSAGE, + number=8, + oneof="stream_type_info", + message="DaiSession.AdBreak.VodBreak", + ) + pod_keys: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=1, + ) + ad_break_id: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + break_type: dai_session_enums.BreakTypeEnum.BreakType = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum=dai_session_enums.BreakTypeEnum.BreakType, + ) + break_sequence: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + served_ads_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + executed_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + tracking_pings: MutableMapping[int, "DaiSession.AdBreak.TrackingPing"] = ( + proto.MapField( + proto.INT64, + proto.MESSAGE, + number=9, + message="DaiSession.AdBreak.TrackingPing", + ) + ) + + class HttpRequest(proto.Message): + r"""An HTTP request made by DAI. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + request_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the request was + made. + latency (google.protobuf.duration_pb2.Duration): + Output only. How long the request took to + complete. + url (str): + Output only. The URL sent in the request. + + This field is a member of `oneof`_ ``_url``. + user_agent (str): + Output only. The user agent sent with the + request. + + This field is a member of `oneof`_ ``_user_agent``. + response_code (int): + Output only. The HTTP response code. + + This field is a member of `oneof`_ ``_response_code``. + response_body (str): + Output only. The full response body. + + This field is a member of `oneof`_ ``_response_body``. + """ + + request_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + url: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + user_agent: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + response_code: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + response_body: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + class Creative(proto.Message): + r"""Information about a single creative. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id_type (google.ads.admanager_v1.types.CreativeIdTypeEnum.CreativeIdType): + Output only. The type of ID that is used to + identify this creative. + + This field is a member of `oneof`_ ``_id_type``. + id_value (str): + Output only. The value for the given ID type. + + This field is a member of `oneof`_ ``_id_value``. + ad_system (str): + Output only. The ad system that provided this + creative. + + This field is a member of `oneof`_ ``_ad_system``. + duration (google.protobuf.duration_pb2.Duration): + Output only. Duration of the creative. + pod_sequence (int): + Output only. The index at which this creative + appeared in the ad pod. + + This field is a member of `oneof`_ ``_pod_sequence``. + vast_infos (MutableSequence[google.ads.admanager_v1.types.DaiSession.Creative.VastInfo]): + Output only. The VAST infos that resulted in + this creative. + ad_buffet (bool): + Output only. Whether this creative was from + ad buffet. + + This field is a member of `oneof`_ ``_ad_buffet``. + """ + + class VastInfo(proto.Message): + r"""Details about a single VAST info. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ad_system (str): + Output only. Value of + VAST/Ad/InLine/AdSystem. + + This field is a member of `oneof`_ ``_ad_system``. + ad_system_version (str): + Output only. Version attribute from + VAST/Ad/InLine/AdSystem. + + This field is a member of `oneof`_ ``_ad_system_version``. + ad_title (str): + Output only. Value of VAST/Ad/InLine/AdTitle. + + This field is a member of `oneof`_ ``_ad_title``. + description (str): + Output only. Value of + VAST/Ad/InLine/Description. + + This field is a member of `oneof`_ ``_description``. + creative_id (str): + Output only. The ``id`` attribute from + VAST/Ad/InLine/Creatives/Creative. + + This field is a member of `oneof`_ ``_creative_id``. + """ + + ad_system: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + ad_system_version: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + ad_title: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + creative_id: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + id_type: dai_session_enums.CreativeIdTypeEnum.CreativeIdType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.CreativeIdTypeEnum.CreativeIdType, + ) + id_value: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + ad_system: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + pod_sequence: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + vast_infos: MutableSequence["DaiSession.Creative.VastInfo"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=6, + message="DaiSession.Creative.VastInfo", + ) + ) + ad_buffet: bool = proto.Field( + proto.BOOL, + number=7, + optional=True, + ) + + class Finding(proto.Message): + r"""Information about errors or notable discoveries that occurred + during a session. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pod_finding (google.ads.admanager_v1.types.DaiSession.Finding.PodFinding): + Output only. A finding related to building an + ad pod. + + This field is a member of `oneof`_ ``type``. + slate_finding (google.ads.admanager_v1.types.DaiSession.Finding.SlateFinding): + Output only. A finding related to the slate + creative. + + This field is a member of `oneof`_ ``type``. + ad_break_finding (google.ads.admanager_v1.types.DaiSession.Finding.AdBreakFinding): + Output only. A finding related to an ad + break. + + This field is a member of `oneof`_ ``type``. + tracking_finding (google.ads.admanager_v1.types.DaiSession.Finding.TrackingPingFinding): + Output only. A finding related to a tracking + ping. + + This field is a member of `oneof`_ ``type``. + creative_finding (google.ads.admanager_v1.types.DaiSession.Finding.CreativeFinding): + Output only. A finding related to a creative. + + This field is a member of `oneof`_ ``type``. + ad_request_finding (google.ads.admanager_v1.types.DaiSession.Finding.AdRequestFinding): + Output only. A finding related to an ad + request within ad selection. + + This field is a member of `oneof`_ ``type``. + severity (google.ads.admanager_v1.types.SessionFindingSeverityEnum.SessionFindingSeverity): + Output only. The severity of the finding to + the session. + + This field is a member of `oneof`_ ``_severity``. + description (str): + Output only. A description of the finding. + + This field is a member of `oneof`_ ``_description``. + """ + + class PodFinding(proto.Message): + r"""A finding that occurred while decisioning an ad pod. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.ads.admanager_v1.types.PodFindingTypeEnum.PodFindingType): + Output only. The finding's type. + + This field is a member of `oneof`_ ``_type``. + pod_key (int): + Output only. ID that links to the relevant ad + pod. + + This field is a member of `oneof`_ ``_pod_key``. + """ + + type_: dai_session_enums.PodFindingTypeEnum.PodFindingType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.PodFindingTypeEnum.PodFindingType, + ) + pod_key: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + class SlateFinding(proto.Message): + r"""A finding that occurred regarding the slate creative, which can be + found at the + [DaiSession.slate][google.ads.admanager.v1.DaiSession.slate] field. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.ads.admanager_v1.types.SlateFindingTypeEnum.SlateFindingType): + Output only. The finding's type. + + This field is a member of `oneof`_ ``_type``. + """ + + type_: dai_session_enums.SlateFindingTypeEnum.SlateFindingType = ( + proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.SlateFindingTypeEnum.SlateFindingType, + ) + ) + + class AdBreakFinding(proto.Message): + r"""A finding that occurred while serving ads for a session. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.ads.admanager_v1.types.AdBreakFindingTypeEnum.AdBreakFindingType): + Output only. The finding's type. + + This field is a member of `oneof`_ ``_type``. + break_key (int): + Output only. The ID that links to the + relevant ad break. + + This field is a member of `oneof`_ ``_break_key``. + """ + + type_: dai_session_enums.AdBreakFindingTypeEnum.AdBreakFindingType = ( + proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.AdBreakFindingTypeEnum.AdBreakFindingType, + ) + ) + break_key: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + class TrackingPingFinding(proto.Message): + r"""A finding that occurred while pinging tracking URLs for a + session. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.ads.admanager_v1.types.TrackingPingFindingTypeEnum.TrackingPingFindingType): + Output only. The finding's type. + + This field is a member of `oneof`_ ``_type``. + tracking_ping_key (int): + Output only. The ID that links to the + relevant tracking ping. + + This field is a member of `oneof`_ ``_tracking_ping_key``. + """ + + type_: dai_session_enums.TrackingPingFindingTypeEnum.TrackingPingFindingType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.TrackingPingFindingTypeEnum.TrackingPingFindingType, + ) + tracking_ping_key: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + class CreativeFinding(proto.Message): + r"""A finding that occurred while looking up creative + information. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.ads.admanager_v1.types.CreativeFindingTypeEnum.CreativeFindingType): + Output only. The finding's type. + + This field is a member of `oneof`_ ``_type``. + creative_key (int): + Output only. The ID that links to the + relevant creative. + + This field is a member of `oneof`_ ``_creative_key``. + """ + + type_: dai_session_enums.CreativeFindingTypeEnum.CreativeFindingType = ( + proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.CreativeFindingTypeEnum.CreativeFindingType, + ) + ) + creative_key: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + class AdRequestFinding(proto.Message): + r"""A finding that occurred while making an ad request. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.ads.admanager_v1.types.AdRequestFindingTypeEnum.AdRequestFindingType): + Output only. The finding's type. + + This field is a member of `oneof`_ ``_type``. + ad_selection_key (int): + Output only. The ID that links to the + relevant ad selection. + + This field is a member of `oneof`_ ``_ad_selection_key``. + ad_request_key (int): + Output only. The ID that links to the + relevant ad request. + + This field is a member of `oneof`_ ``_ad_request_key``. + """ + + type_: dai_session_enums.AdRequestFindingTypeEnum.AdRequestFindingType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.AdRequestFindingTypeEnum.AdRequestFindingType, + ) + ad_selection_key: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + ad_request_key: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + + pod_finding: "DaiSession.Finding.PodFinding" = proto.Field( + proto.MESSAGE, + number=4, + oneof="type", + message="DaiSession.Finding.PodFinding", + ) + slate_finding: "DaiSession.Finding.SlateFinding" = proto.Field( + proto.MESSAGE, + number=5, + oneof="type", + message="DaiSession.Finding.SlateFinding", + ) + ad_break_finding: "DaiSession.Finding.AdBreakFinding" = proto.Field( + proto.MESSAGE, + number=6, + oneof="type", + message="DaiSession.Finding.AdBreakFinding", + ) + tracking_finding: "DaiSession.Finding.TrackingPingFinding" = proto.Field( + proto.MESSAGE, + number=7, + oneof="type", + message="DaiSession.Finding.TrackingPingFinding", + ) + creative_finding: "DaiSession.Finding.CreativeFinding" = proto.Field( + proto.MESSAGE, + number=8, + oneof="type", + message="DaiSession.Finding.CreativeFinding", + ) + ad_request_finding: "DaiSession.Finding.AdRequestFinding" = proto.Field( + proto.MESSAGE, + number=9, + oneof="type", + message="DaiSession.Finding.AdRequestFinding", + ) + severity: dai_session_enums.SessionFindingSeverityEnum.SessionFindingSeverity = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=dai_session_enums.SessionFindingSeverityEnum.SessionFindingSeverity, + ) + description: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + creation_context: CreationContext = proto.Field( + proto.MESSAGE, + number=3, + message=CreationContext, + ) + slate: Creative = proto.Field( + proto.MESSAGE, + number=4, + message=Creative, + ) + ad_selections: MutableMapping[int, AdSelection] = proto.MapField( + proto.INT64, + proto.MESSAGE, + number=5, + message=AdSelection, + ) + ad_pods: MutableMapping[int, AdPod] = proto.MapField( + proto.INT64, + proto.MESSAGE, + number=6, + message=AdPod, + ) + ad_breaks: MutableMapping[int, AdBreak] = proto.MapField( + proto.INT64, + proto.MESSAGE, + number=7, + message=AdBreak, + ) + findings: MutableSequence[Finding] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=Finding, + ) + session_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_service.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_service.py new file mode 100644 index 000000000000..85d1bb0a19c8 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/dai_session_service.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.ads.admanager.v1", + manifest={ + "GetDaiSessionRequest", + }, +) + + +class GetDaiSessionRequest(proto.Message): + r"""Request object for ``GetDaiSession`` method. + + Attributes: + name (str): + Required. The resource name of the DaiSession. The + dai_session can be either the session ID or debug key, that + DAI returns on stream create. For details, see `Locate a DAI + session ID or debug + key `__. + + Format: + ``networks/{network_code}/daiSessions/{dai_session}`` + Format: ``networks/{network_code}/daiSessions/{session_id}`` + Format: ``networks/{network_code}/daiSessions/{debug_key}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_messages.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_messages.py index c42006218096..8f235cc2619d 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_messages.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_messages.py @@ -74,6 +74,14 @@ class PrivateAuctionDeal(proto.Message): Optional. The targeting of the ``PrivateAuctionDeal``. This field is a member of `oneof`_ ``_targeting``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Non-empty default. The start time of the + ``PrivateAuctionDeal``. If unset, the ``startTime`` will + default as follows: On create: To the deal's + ``create_time``. On update: To the deal's existing + ``start_time``, which can be null. + + This field is a member of `oneof`_ ``_start_time``. end_time (google.protobuf.timestamp_pb2.Timestamp): Optional. The end time of the ``PrivateAuctionDeal``. @@ -99,6 +107,11 @@ class PrivateAuctionDeal(proto.Message): enabled. This field is a member of `oneof`_ ``_block_override_enabled``. + publisher_floor_exempt (bool): + Optional. Whether the deal is exempt from + publisher floor price. + + This field is a member of `oneof`_ ``_publisher_floor_exempt``. buyer_permission_type (google.ads.admanager_v1.types.DealBuyerPermissionTypeEnum.DealBuyerPermissionType): Optional. The buyer permission model defining how the deal would transact among all buyers @@ -115,6 +128,10 @@ class PrivateAuctionDeal(proto.Message): non-guaranteed deals. This field is a member of `oneof`_ ``_deal_priority``. + archived (bool): + Output only. Whether the deal is archived. + + This field is a member of `oneof`_ ``_archived``. create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The instant at which the ``PrivateAuctionDeal`` was created. @@ -177,6 +194,12 @@ class BuyerData(proto.Message): optional=True, message=gaa_targeting.Targeting, ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=26, + optional=True, + message=timestamp_pb2.Timestamp, + ) end_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=8, @@ -210,6 +233,11 @@ class BuyerData(proto.Message): number=12, optional=True, ) + publisher_floor_exempt: bool = proto.Field( + proto.BOOL, + number=24, + optional=True, + ) buyer_permission_type: deal_buyer_permission_type_enum.DealBuyerPermissionTypeEnum.DealBuyerPermissionType = proto.Field( proto.ENUM, number=13, @@ -228,6 +256,11 @@ class BuyerData(proto.Message): optional=True, message=non_guaranteed_deal_priority.NonGuaranteedDealPriority, ) + archived: bool = proto.Field( + proto.BOOL, + number=23, + optional=True, + ) create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=15, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_service.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_service.py index 22ce96ea77f8..1269c4075858 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_service.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/private_auction_deal_service.py @@ -78,6 +78,7 @@ class ListPrivateAuctionDealsRequest(proto.Message): **Filterable fields:** + - ``archived`` - ``auctionPriorityEnabled`` - ``blockOverrideEnabled`` - ``buyerAccountId`` @@ -89,6 +90,7 @@ class ListPrivateAuctionDealsRequest(proto.Message): - ``privateAuctionDealId`` - ``privateAuctionDisplayName`` - ``privateAuctionId`` + - ``publisherFloorExempt`` - ``status`` - ``updateTime`` order_by (str): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py index 2f214ed3c1c9..9f2d8d4b2174 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py @@ -13759,8 +13759,8 @@ class Slice(proto.Message): class Flag(proto.Message): r"""A flag for a report. Flags are used show if certain thresholds are met. Result rows that match the filter will have the corresponding - [MetricValueGroup.flagValues][MetricValueGroup] index set to true. - For more information about flags see: + [ReportDataTable.MetricValueGroup.flagValues][google.ads.admanager.v1.ReportDataTable.MetricValueGroup.flag_values] + index set to true. For more information about flags see: https://support.google.com/admanager/answer/15079975 Attributes: diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_delivery.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_delivery.py index 5460bc9189ae..32e5f882bce8 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_delivery.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_delivery.py @@ -89,9 +89,10 @@ class Schedule(proto.Message): frequency (google.ads.admanager_v1.types.ScheduleOptions.Schedule.Frequency): Frequency to run report. start_time (google.type.timeofday_pb2.TimeOfDay): - Indicates start time for schedule to run Will use the - time_zone from ``ReportDefinition``. Defaults to the - publisher's time zone if not specified. + Indicates start time for schedule to run. Will use the + time_zone from + [ReportDefinition][google.ads.admanager.v1.ReportDefinition]. + Defaults to the publisher's time zone if not specified. For HOURLY, TWO_TIMES_DAILY, THREE_TIMES_DAILY, or FOUR_TIMES_DAILY, this will be the time of day that the diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_visibility_enum.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_visibility_enum.py index 546710381659..fcfee4485e08 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_visibility_enum.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_visibility_enum.py @@ -28,7 +28,10 @@ class ReportVisibilityEnum(proto.Message): - r"""Wrapper message for ReportVisibility enum.""" + r"""Wrapper message for + [ReportVisibility][google.ads.admanager.v1.ReportVisibilityEnum.ReportVisibility]. + + """ class ReportVisibility(proto.Enum): r"""The visibility of a report. diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_dai_session_service_get_dai_session_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_dai_session_service_get_dai_session_sync.py new file mode 100644 index 000000000000..3af5d77288b8 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_dai_session_service_get_dai_session_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDaiSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_DaiSessionService_GetDaiSession_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import admanager_v1 + + +def sample_get_dai_session(): + # Create a client + client = admanager_v1.DaiSessionServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetDaiSessionRequest( + name="name_value", + ) + + # Make the request + response = client.get_dai_session(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_DaiSessionService_GetDaiSession_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json b/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json index 4c21685c1783..a45333953f28 100644 --- a/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json +++ b/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-ads-admanager", - "version": "0.10.4" + "version": "0.10.5" }, "snippets": [ { @@ -13377,6 +13377,86 @@ ], "title": "admanager_v1_generated_dai_encoding_profile_service_update_dai_encoding_profile_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.DaiSessionServiceClient", + "shortName": "DaiSessionServiceClient" + }, + "fullName": "google.ads.admanager_v1.DaiSessionServiceClient.get_dai_session", + "method": { + "fullName": "google.ads.admanager.v1.DaiSessionService.GetDaiSession", + "service": { + "fullName": "google.ads.admanager.v1.DaiSessionService", + "shortName": "DaiSessionService" + }, + "shortName": "GetDaiSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.GetDaiSessionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.types.DaiSession", + "shortName": "get_dai_session" + }, + "description": "Sample for GetDaiSession", + "file": "admanager_v1_generated_dai_session_service_get_dai_session_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_DaiSessionService_GetDaiSession_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "admanager_v1_generated_dai_session_service_get_dai_session_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_dai_session_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_dai_session_service.py new file mode 100644 index 000000000000..72158ca2bf71 --- /dev/null +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_dai_session_service.py @@ -0,0 +1,1880 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.ads.admanager_v1.services.dai_session_service import ( + DaiSessionServiceClient, + transports, +) +from google.ads.admanager_v1.types import dai_session_messages, dai_session_service + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert DaiSessionServiceClient._get_client_cert_source(None, False) is None + assert ( + DaiSessionServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + DaiSessionServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + DaiSessionServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + DaiSessionServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = DaiSessionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = DaiSessionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DaiSessionServiceClient, "rest"), + ], +) +def test_dai_session_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "admanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.DaiSessionServiceRestTransport, "rest"), + ], +) +def test_dai_session_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DaiSessionServiceClient, "rest"), + ], +) +def test_dai_session_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "admanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com" + ) + + +def test_dai_session_service_client_get_transport_class(): + transport = DaiSessionServiceClient.get_transport_class() + available_transports = [ + transports.DaiSessionServiceRestTransport, + ] + assert transport in available_transports + + transport = DaiSessionServiceClient.get_transport_class("rest") + assert transport == transports.DaiSessionServiceRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DaiSessionServiceClient, transports.DaiSessionServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + DaiSessionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DaiSessionServiceClient), +) +def test_dai_session_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DaiSessionServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DaiSessionServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + DaiSessionServiceClient, + transports.DaiSessionServiceRestTransport, + "rest", + "true", + ), + ( + DaiSessionServiceClient, + transports.DaiSessionServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + DaiSessionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DaiSessionServiceClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dai_session_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [DaiSessionServiceClient]) +@mock.patch.object( + DaiSessionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DaiSessionServiceClient), +) +def test_dai_session_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [DaiSessionServiceClient]) +@mock.patch.object( + DaiSessionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DaiSessionServiceClient), +) +def test_dai_session_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DaiSessionServiceClient._DEFAULT_UNIVERSE + default_endpoint = DaiSessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = DaiSessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DaiSessionServiceClient, transports.DaiSessionServiceRestTransport, "rest"), + ], +) +def test_dai_session_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + DaiSessionServiceClient, + transports.DaiSessionServiceRestTransport, + "rest", + None, + ), + ], +) +def test_dai_session_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_get_dai_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_dai_session in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_dai_session] = mock_rpc + + request = {} + client.get_dai_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_dai_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_dai_session_rest_required_fields( + request_type=dai_session_service.GetDaiSessionRequest, +): + transport_class = transports.DaiSessionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetDaiSession, + "_BaseGetDaiSession__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dai_session_messages.DaiSession() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dai_session_messages.DaiSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_dai_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_dai_session_rest_flattened(): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dai_session_messages.DaiSession() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "networks/sample1/daiSessions/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dai_session_messages.DaiSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_dai_session(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=networks/*/daiSessions/*}" % client.transport._host, args[1] + ) + + +def test_get_dai_session_rest_flattened_error(transport: str = "rest"): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_dai_session( + dai_session_service.GetDaiSessionRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DaiSessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DaiSessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DaiSessionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DaiSessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DaiSessionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DaiSessionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DaiSessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DaiSessionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DaiSessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DaiSessionServiceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DaiSessionServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = DaiSessionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_dai_session_rest_bad_request( + request_type=dai_session_service.GetDaiSessionRequest, +): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/daiSessions/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_dai_session(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dai_session_service.GetDaiSessionRequest, + dict, + ], +) +def test_get_dai_session_rest_call_success(request_type): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/daiSessions/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dai_session_messages.DaiSession( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dai_session_messages.DaiSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_dai_session(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dai_session_messages.DaiSession) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_dai_session_rest_interceptors(null_interceptor): + transport = transports.DaiSessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DaiSessionServiceRestInterceptor(), + ) + client = DaiSessionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DaiSessionServiceRestInterceptor, "post_get_dai_session" + ) as post, + mock.patch.object( + transports.DaiSessionServiceRestInterceptor, + "post_get_dai_session_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DaiSessionServiceRestInterceptor, "pre_get_dai_session" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dai_session_service.GetDaiSessionRequest.pb( + dai_session_service.GetDaiSessionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = dai_session_messages.DaiSession.to_json( + dai_session_messages.DaiSession() + ) + req.return_value.content = return_value + + request = dai_session_service.GetDaiSessionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dai_session_messages.DaiSession() + post_with_metadata.return_value = dai_session_messages.DaiSession(), metadata + + client.get_dai_session( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "networks/sample1/operations/reports/runs/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "networks/sample1/operations/reports/runs/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "networks/sample1/operations/reports/runs/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "networks/sample1/operations/reports/runs/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_dai_session_empty_call_rest(): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_dai_session), "__call__") as call: + client.get_dai_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dai_session_service.GetDaiSessionRequest() + assert args[0] == request_msg + + +def test_dai_session_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DaiSessionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_dai_session_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.ads.admanager_v1.services.dai_session_service.transports.DaiSessionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DaiSessionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_dai_session", + "get_operation", + "cancel_operation", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dai_session_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.ads.admanager_v1.services.dai_session_service.transports.DaiSessionServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DaiSessionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ), + quota_project_id="octopus", + ) + + +def test_dai_session_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.ads.admanager_v1.services.dai_session_service.transports.DaiSessionServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DaiSessionServiceTransport() + adc.assert_called_once() + + +def test_dai_session_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DaiSessionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ), + quota_project_id=None, + ) + + +def test_dai_session_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DaiSessionServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_dai_session_service_host_no_port(transport_name): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="admanager.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "admanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_dai_session_service_host_with_port(transport_name): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="admanager.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "admanager.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_dai_session_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DaiSessionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DaiSessionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_dai_session._session + session2 = client2.transport.get_dai_session._session + assert session1 != session2 + + +def test_content_path(): + network_code = "squid" + content = "clam" + expected = "networks/{network_code}/content/{content}".format( + network_code=network_code, + content=content, + ) + actual = DaiSessionServiceClient.content_path(network_code, content) + assert expected == actual + + +def test_parse_content_path(): + expected = { + "network_code": "whelk", + "content": "octopus", + } + path = DaiSessionServiceClient.content_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_content_path(path) + assert expected == actual + + +def test_dai_session_path(): + network_code = "oyster" + dai_session = "nudibranch" + expected = "networks/{network_code}/daiSessions/{dai_session}".format( + network_code=network_code, + dai_session=dai_session, + ) + actual = DaiSessionServiceClient.dai_session_path(network_code, dai_session) + assert expected == actual + + +def test_parse_dai_session_path(): + expected = { + "network_code": "cuttlefish", + "dai_session": "mussel", + } + path = DaiSessionServiceClient.dai_session_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_dai_session_path(path) + assert expected == actual + + +def test_live_stream_path(): + network_code = "winkle" + live_stream = "nautilus" + expected = "networks/{network_code}/liveStreams/{live_stream}".format( + network_code=network_code, + live_stream=live_stream, + ) + actual = DaiSessionServiceClient.live_stream_path(network_code, live_stream) + assert expected == actual + + +def test_parse_live_stream_path(): + expected = { + "network_code": "scallop", + "live_stream": "abalone", + } + path = DaiSessionServiceClient.live_stream_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_live_stream_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = DaiSessionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DaiSessionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = DaiSessionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DaiSessionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = DaiSessionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DaiSessionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = DaiSessionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DaiSessionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = DaiSessionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DaiSessionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DaiSessionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.DaiSessionServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.DaiSessionServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = DaiSessionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = DaiSessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (DaiSessionServiceClient, transports.DaiSessionServiceRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_private_auction_deal_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_private_auction_deal_service.py index 470a283c4703..fc2eb70bab90 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_private_auction_deal_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_private_auction_deal_service.py @@ -1891,7 +1891,9 @@ def test_get_private_auction_deal_rest_call_success(request_type): status=private_marketplace_enums.PrivateMarketplaceDealStatusEnum.PrivateMarketplaceDealStatus.PENDING, auction_priority_enabled=True, block_override_enabled=True, + publisher_floor_exempt=True, buyer_permission_type=deal_buyer_permission_type_enum.DealBuyerPermissionTypeEnum.DealBuyerPermissionType.NEGOTIATOR_ONLY, + archived=True, ) # Wrap the value into a proper Response obj @@ -1920,10 +1922,12 @@ def test_get_private_auction_deal_rest_call_success(request_type): ) assert response.auction_priority_enabled is True assert response.block_override_enabled is True + assert response.publisher_floor_exempt is True assert ( response.buyer_permission_type == deal_buyer_permission_type_enum.DealBuyerPermissionTypeEnum.DealBuyerPermissionType.NEGOTIATOR_ONLY ) + assert response.archived is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -2411,7 +2415,8 @@ def test_create_private_auction_deal_rest_call_success(request_type): } }, }, - "end_time": {"seconds": 751, "nanos": 543}, + "start_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, "floor_price": { "currency_code": "currency_code_value", "units": 563, @@ -2421,9 +2426,11 @@ def test_create_private_auction_deal_rest_call_success(request_type): "status": 1, "auction_priority_enabled": True, "block_override_enabled": True, + "publisher_floor_exempt": True, "buyer_permission_type": 1, "buyer_data": {"buyer_emails": ["buyer_emails_value1", "buyer_emails_value2"]}, "deal_priority": {"priority_tier": 1}, + "archived": True, "create_time": {}, "update_time": {}, } @@ -2515,7 +2522,9 @@ def get_message_fields(field): status=private_marketplace_enums.PrivateMarketplaceDealStatusEnum.PrivateMarketplaceDealStatus.PENDING, auction_priority_enabled=True, block_override_enabled=True, + publisher_floor_exempt=True, buyer_permission_type=deal_buyer_permission_type_enum.DealBuyerPermissionTypeEnum.DealBuyerPermissionType.NEGOTIATOR_ONLY, + archived=True, ) # Wrap the value into a proper Response obj @@ -2544,10 +2553,12 @@ def get_message_fields(field): ) assert response.auction_priority_enabled is True assert response.block_override_enabled is True + assert response.publisher_floor_exempt is True assert ( response.buyer_permission_type == deal_buyer_permission_type_enum.DealBuyerPermissionTypeEnum.DealBuyerPermissionType.NEGOTIATOR_ONLY ) + assert response.archived is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -2893,7 +2904,8 @@ def test_update_private_auction_deal_rest_call_success(request_type): } }, }, - "end_time": {"seconds": 751, "nanos": 543}, + "start_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, "floor_price": { "currency_code": "currency_code_value", "units": 563, @@ -2903,9 +2915,11 @@ def test_update_private_auction_deal_rest_call_success(request_type): "status": 1, "auction_priority_enabled": True, "block_override_enabled": True, + "publisher_floor_exempt": True, "buyer_permission_type": 1, "buyer_data": {"buyer_emails": ["buyer_emails_value1", "buyer_emails_value2"]}, "deal_priority": {"priority_tier": 1}, + "archived": True, "create_time": {}, "update_time": {}, } @@ -2997,7 +3011,9 @@ def get_message_fields(field): status=private_marketplace_enums.PrivateMarketplaceDealStatusEnum.PrivateMarketplaceDealStatus.PENDING, auction_priority_enabled=True, block_override_enabled=True, + publisher_floor_exempt=True, buyer_permission_type=deal_buyer_permission_type_enum.DealBuyerPermissionTypeEnum.DealBuyerPermissionType.NEGOTIATOR_ONLY, + archived=True, ) # Wrap the value into a proper Response obj @@ -3026,10 +3042,12 @@ def get_message_fields(field): ) assert response.auction_priority_enabled is True assert response.block_override_enabled is True + assert response.publisher_floor_exempt is True assert ( response.buyer_permission_type == deal_buyer_permission_type_enum.DealBuyerPermissionTypeEnum.DealBuyerPermissionType.NEGOTIATOR_ONLY ) + assert response.archived is True @pytest.mark.parametrize("null_interceptor", [True, False]) diff --git a/packages/google-ads-datamanager/CHANGELOG.md b/packages/google-ads-datamanager/CHANGELOG.md index ffb869651a3c..58b0ed00e80d 100644 --- a/packages/google-ads-datamanager/CHANGELOG.md +++ b/packages/google-ads-datamanager/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-ads-datamanager/#history +## [0.9.3](https://github.com/googleapis/google-cloud-python/compare/google-ads-datamanager-v0.9.2...google-ads-datamanager-v0.9.3) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.9.2](https://github.com/googleapis/google-cloud-python/compare/google-ads-datamanager-v0.9.1...google-ads-datamanager-v0.9.2) (2026-08-21) diff --git a/packages/google-ads-datamanager/google/ads/datamanager/gapic_version.py b/packages/google-ads-datamanager/google/ads/datamanager/gapic_version.py index fb586dd114ef..c3ac4f9ff781 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager/gapic_version.py +++ b/packages/google-ads-datamanager/google/ads/datamanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.2" # {x-release-please-version} +__version__ = "0.9.3" # {x-release-please-version} diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/gapic_version.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/gapic_version.py index fb586dd114ef..c3ac4f9ff781 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/gapic_version.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.2" # {x-release-please-version} +__version__ = "0.9.3" # {x-release-please-version} diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/async_client.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/async_client.py index be18d079db69..fac09fa7b43e 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/async_client.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/async_client.py @@ -329,8 +329,7 @@ async def sample_ingest_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" @@ -424,8 +423,7 @@ async def sample_remove_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" @@ -517,8 +515,7 @@ async def sample_remove_all_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.RemoveAllAudienceMembersRequest( destinations=destinations, @@ -605,8 +602,7 @@ async def sample_ingest_events(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.IngestEventsRequest( destinations=destinations, @@ -708,15 +704,8 @@ async def sample_ingest_ad_events(): ad_events.medium = "medium_value" ad_events.viewability_info.view_type = "VIEW_TYPE_MRC_RENDERED" - encryption_info = datamanager_v1.EncryptionInfo() - encryption_info.gcp_wrapped_key_info.key_type = "XCHACHA20_POLY1305" - encryption_info.gcp_wrapped_key_info.wip_provider = "wip_provider_value" - encryption_info.gcp_wrapped_key_info.kek_uri = "kek_uri_value" - encryption_info.gcp_wrapped_key_info.encrypted_dek = "encrypted_dek_value" - request = datamanager_v1.IngestAdEventsRequest( ad_events=ad_events, - encryption_info=encryption_info, ) # Make the request diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/client.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/client.py index bacd64646a63..267c0531037e 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/client.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/client.py @@ -607,8 +607,7 @@ def sample_ingest_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" @@ -700,8 +699,7 @@ def sample_remove_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" @@ -791,8 +789,7 @@ def sample_remove_all_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.RemoveAllAudienceMembersRequest( destinations=destinations, @@ -879,8 +876,7 @@ def sample_ingest_events(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.IngestEventsRequest( destinations=destinations, @@ -980,15 +976,8 @@ def sample_ingest_ad_events(): ad_events.medium = "medium_value" ad_events.viewability_info.view_type = "VIEW_TYPE_MRC_RENDERED" - encryption_info = datamanager_v1.EncryptionInfo() - encryption_info.gcp_wrapped_key_info.key_type = "XCHACHA20_POLY1305" - encryption_info.gcp_wrapped_key_info.wip_provider = "wip_provider_value" - encryption_info.gcp_wrapped_key_info.kek_uri = "kek_uri_value" - encryption_info.gcp_wrapped_key_info.encrypted_dek = "encrypted_dek_value" - request = datamanager_v1.IngestAdEventsRequest( ad_events=ad_events, - encryption_info=encryption_info, ) # Make the request diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/base.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/base.py index 765831d835ba..d539e6aee9f2 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/base.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/base.py @@ -142,12 +142,32 @@ def _prep_wrapped_messages(self, client_info): self._wrapped_methods = { self.ingest_audience_members: gapic_v1.method.wrap_method( self.ingest_audience_members, - default_timeout=None, + default_retry=retries.Retry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, client_info=client_info, ), self.remove_audience_members: gapic_v1.method.wrap_method( self.remove_audience_members, - default_timeout=None, + default_retry=retries.Retry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, client_info=client_info, ), self.remove_all_audience_members: gapic_v1.method.wrap_method( @@ -157,7 +177,17 @@ def _prep_wrapped_messages(self, client_info): ), self.ingest_events: gapic_v1.method.wrap_method( self.ingest_events, - default_timeout=None, + default_retry=retries.Retry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, client_info=client_info, ), self.ingest_ad_events: gapic_v1.method.wrap_method( @@ -167,7 +197,17 @@ def _prep_wrapped_messages(self, client_info): ), self.retrieve_request_status: gapic_v1.method.wrap_method( self.retrieve_request_status, - default_timeout=None, + default_retry=retries.Retry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), } diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/grpc_asyncio.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/grpc_asyncio.py index 23b85b166483..81b6d5b22da4 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/grpc_asyncio.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/ingestion_service/transports/grpc_asyncio.py @@ -526,12 +526,32 @@ def _prep_wrapped_messages(self, client_info): self._wrapped_methods = { self.ingest_audience_members: self._wrap_method( self.ingest_audience_members, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, client_info=client_info, ), self.remove_audience_members: self._wrap_method( self.remove_audience_members, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, client_info=client_info, ), self.remove_all_audience_members: self._wrap_method( @@ -541,7 +561,17 @@ def _prep_wrapped_messages(self, client_info): ), self.ingest_events: self._wrap_method( self.ingest_events, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, client_info=client_info, ), self.ingest_ad_events: self._wrap_method( @@ -551,7 +581,17 @@ def _prep_wrapped_messages(self, client_info): ), self.retrieve_request_status: self._wrap_method( self.retrieve_request_status, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=5.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), } diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/async_client.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/async_client.py index e8d331e28b58..89bb39c1fbca 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/async_client.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/async_client.py @@ -343,9 +343,9 @@ async def sample_create_partner_link(): # Initialize request argument(s) partner_link = datamanager_v1.PartnerLink() partner_link.owning_account.account_id = "account_id_value" - partner_link.owning_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.owning_account.account_type = "GOOGLE_AD_MANAGER" partner_link.partner_account.account_id = "account_id_value" - partner_link.partner_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.partner_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.CreatePartnerLinkRequest( parent="parent_value", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/client.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/client.py index 443bf615b898..6a2ea8ca0d2d 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/client.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/client.py @@ -637,9 +637,9 @@ def sample_create_partner_link(): # Initialize request argument(s) partner_link = datamanager_v1.PartnerLink() partner_link.owning_account.account_id = "account_id_value" - partner_link.owning_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.owning_account.account_type = "GOOGLE_AD_MANAGER" partner_link.partner_account.account_id = "account_id_value" - partner_link.partner_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.partner_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.CreatePartnerLinkRequest( parent="parent_value", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ad_event.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ad_event.py index 9bac944e3475..8ee3c1d071bc 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ad_event.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ad_event.py @@ -318,6 +318,12 @@ class AdEvent(proto.Message): device_info (google.ads.datamanager_v1.types.DeviceInfo): Required. Information gathered about the device being used when the ad event happened. + ip_address (str): + Optional. IP address used for measurement. This must be same + value as + [DeviceInfo.ip_address][google.ads.datamanager.v1.DeviceInfo.ip_address]. + Keep it blank if you do not want to share IP for + measurement. mobile_device_id (str): Optional. The device ID of the device that the ad was served to. @@ -487,6 +493,10 @@ class EventSubtype(proto.Enum): number=8, message=gad_device_info.DeviceInfo, ) + ip_address: str = proto.Field( + proto.STRING, + number=34, + ) mobile_device_id: str = proto.Field( proto.STRING, number=9, diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py index a09a0b7e100c..6c7e4d6d0317 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py @@ -88,10 +88,14 @@ class Destination(proto.Message): Required. The account to send the data to or remove the data from. product_destination_id (str): - Required. The object within the product + Optional. The object within the product account to ingest into. For example, a Google Ads audience ID, a Display & Video 360 audience ID or a Google Ads conversion action ID. + + This field is optional for Google Ad Manager + event ingestion and User ingestion. Required for + all other use cases. """ reference: str = proto.Field( @@ -158,6 +162,8 @@ class AccountType(proto.Enum): Google Ad Manager audience link. FLOODLIGHT_CONFIG (7): Floodlight configuration. + GOOGLE_AD_MANAGER (8): + Google Ad Manager. """ ACCOUNT_TYPE_UNSPECIFIED = 0 @@ -168,6 +174,7 @@ class AccountType(proto.Enum): GOOGLE_ANALYTICS_PROPERTY = 5 GOOGLE_AD_MANAGER_AUDIENCE_LINK = 6 FLOODLIGHT_CONFIG = 7 + GOOGLE_AD_MANAGER = 8 product: "Product" = proto.Field( proto.ENUM, diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py index 095b3221152c..b936b761aac4 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py @@ -38,19 +38,7 @@ class DeviceInfo(proto.Message): ip_address (str): Optional. The IP address of the device for the given context. Required when used in an - [AdEvent][google.ads.datamanager.v1.AdEvent]. - - **Note:** Google Ads does not support IP address matching - for end users in the European Economic Area (EEA), United - Kingdom (UK), or Switzerland (CH). Add logic to - conditionally exclude sharing IP addresses from users from - these regions and ensure that you provide users with clear - and comprehensive information about the data you collect on - your sites, apps, and other properties and get consent where - required by law or any applicable Google policies. See the - `About offline conversion - imports `__ - page for more details. + [AdEvent][google.ads.datamanager.v1.AdEvent] for geo checks. category (str): Optional. The category of device. For example, “desktop”, “tablet”, “mobile”, “smart diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py index 1ab47ed0c540..334ba3a453d2 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py @@ -363,6 +363,13 @@ class ErrorReason(proto.Enum): The remove as of time must be in the past or present. Future timestamps are not permitted for removing audience members. + REQUEST_TOO_OLD (126): + Request status is only available for + approximately 50 days after the API receives a + request. + CONVERSION_ACTION_TOO_RECENTLY_CREATED (127): + The conversion action was created too + recently. """ ERROR_REASON_UNSPECIFIED = 0 @@ -490,6 +497,8 @@ class ErrorReason(proto.Enum): INSIGHTS_MISSING_FOR_DIMENSION = 123 REQUIRED_PREREQUISITE_LINK_MISSING = 124 INVALID_REMOVE_AS_OF_TIME = 125 + REQUEST_TOO_OLD = 126 + CONVERSION_ACTION_TOO_RECENTLY_CREATED = 127 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py index f5c680a71166..d5ec8747d9ca 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py @@ -325,6 +325,14 @@ class AdIdentifiers(proto.Message): this event with a previous event. encrypted_user_ids (MutableSequence[google.ads.datamanager_v1.types.EncryptedUserId]): Optional. Any number of encrypted user IDs. + ppid (str): + Optional. A unique identifier for an + authenticated user (signed-in), as defined by + the publisher. + visitor_ppid (str): + Optional. A unique identifier for an + unauthenticated user (user who is not + signed-in), as defined by the publisher. """ session_attributes: str = proto.Field( @@ -371,6 +379,14 @@ class AdIdentifiers(proto.Message): message=encrypted_user_id.EncryptedUserId, ) ) + ppid: str = proto.Field( + proto.STRING, + number=11, + ) + visitor_ppid: str = proto.Field( + proto.STRING, + number=12, + ) class CustomVariable(proto.Message): diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ingestion_service.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ingestion_service.py index 57bd9ee274a0..313f45077ce0 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ingestion_service.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/ingestion_service.py @@ -96,7 +96,7 @@ class IngestAudienceMembersRequest(proto.Message): validated but not executed. Only errors are returned, not results. encoding (google.ads.datamanager_v1.types.Encoding): - Optional. Required for + Optional. Must be provided for [UserData][google.ads.datamanager.v1.UserData] uploads. The encoding type of the user identifiers. For hashed user identifiers, this is the encoding type of the hashed string. @@ -192,7 +192,7 @@ class RemoveAudienceMembersRequest(proto.Message): validated but not executed. Only errors are returned, not results. encoding (google.ads.datamanager_v1.types.Encoding): - Optional. Required for + Optional. Must be provided for [UserData][google.ads.datamanager.v1.UserData] uploads. The encoding type of the user identifiers. Applies to only the outer encoding for encrypted user identifiers. For non @@ -322,7 +322,7 @@ class IngestEventsRequest(proto.Message): validated but not executed. Only errors are returned, not results. encoding (google.ads.datamanager_v1.types.Encoding): - Optional. Required for + Optional. Must be provided for [UserData][google.ads.datamanager.v1.UserData] uploads. The encoding type of the user identifiers. For hashed user identifiers, this is the encoding type of the hashed string. @@ -402,8 +402,10 @@ class IngestAdEventsRequest(proto.Message): Required. Required (at least 1). A list of ad events. encryption_info (google.ads.datamanager_v1.types.EncryptionInfo): - Required. Information about encryption keys - which are used to encrypt the data. + Optional. Information about encryption keys which are used + to encrypt the data. This field must be provided when ad + events contain + [UserData][google.ads.datamanager.v1.UserData]. validate_only (bool): Optional. If true, the request is validated, but not executed. diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/partner_link_service.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/partner_link_service.py index 58c154b01065..b9091de92e0b 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/partner_link_service.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/partner_link_service.py @@ -157,6 +157,7 @@ class SearchPartnerLinksRequest(proto.Message): feature set, the following fields are also supported: - ``partner_customer_account.account_id`` + - ``partner_link_metadata.implicit_accounts.account_id`` Example: ``owning_account.account_type = "GOOGLE_ADS" AND partner_account.account_id = 987654321`` diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_async.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_async.py index 5e18d94638df..ca99c741c25f 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_async.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_async.py @@ -55,15 +55,8 @@ async def sample_ingest_ad_events(): ad_events.medium = "medium_value" ad_events.viewability_info.view_type = "VIEW_TYPE_MRC_RENDERED" - encryption_info = datamanager_v1.EncryptionInfo() - encryption_info.gcp_wrapped_key_info.key_type = "XCHACHA20_POLY1305" - encryption_info.gcp_wrapped_key_info.wip_provider = "wip_provider_value" - encryption_info.gcp_wrapped_key_info.kek_uri = "kek_uri_value" - encryption_info.gcp_wrapped_key_info.encrypted_dek = "encrypted_dek_value" - request = datamanager_v1.IngestAdEventsRequest( ad_events=ad_events, - encryption_info=encryption_info, ) # Make the request diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_sync.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_sync.py index aa8c1fe63e06..5e9d6a34a082 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_sync.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_ad_events_sync.py @@ -55,15 +55,8 @@ def sample_ingest_ad_events(): ad_events.medium = "medium_value" ad_events.viewability_info.view_type = "VIEW_TYPE_MRC_RENDERED" - encryption_info = datamanager_v1.EncryptionInfo() - encryption_info.gcp_wrapped_key_info.key_type = "XCHACHA20_POLY1305" - encryption_info.gcp_wrapped_key_info.wip_provider = "wip_provider_value" - encryption_info.gcp_wrapped_key_info.kek_uri = "kek_uri_value" - encryption_info.gcp_wrapped_key_info.encrypted_dek = "encrypted_dek_value" - request = datamanager_v1.IngestAdEventsRequest( ad_events=ad_events, - encryption_info=encryption_info, ) # Make the request diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_async.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_async.py index d3ca2dce6215..af87dade288f 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_async.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_async.py @@ -41,8 +41,7 @@ async def sample_ingest_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_sync.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_sync.py index 2250290d10b4..8e99ab6931da 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_sync.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_audience_members_sync.py @@ -41,8 +41,7 @@ def sample_ingest_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_async.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_async.py index f85295c2ba13..7908360d74e5 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_async.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_async.py @@ -41,8 +41,7 @@ async def sample_ingest_events(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.IngestEventsRequest( destinations=destinations, diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_sync.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_sync.py index 855ecf9cff19..de6a6481a89f 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_sync.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_ingest_events_sync.py @@ -41,8 +41,7 @@ def sample_ingest_events(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.IngestEventsRequest( destinations=destinations, diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_async.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_async.py index 618b82b84b35..4ddb59f22b01 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_async.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_async.py @@ -41,8 +41,7 @@ async def sample_remove_all_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.RemoveAllAudienceMembersRequest( destinations=destinations, diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_sync.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_sync.py index 159d2789ca68..6e3cbea9a40d 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_sync.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_all_audience_members_sync.py @@ -41,8 +41,7 @@ def sample_remove_all_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.RemoveAllAudienceMembersRequest( destinations=destinations, diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_async.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_async.py index 1fb0bf52b857..81dc892096eb 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_async.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_async.py @@ -41,8 +41,7 @@ async def sample_remove_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_sync.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_sync.py index b90028e39d52..1f58605f5b70 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_sync.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_ingestion_service_remove_audience_members_sync.py @@ -41,8 +41,7 @@ def sample_remove_audience_members(): # Initialize request argument(s) destinations = datamanager_v1.Destination() destinations.operating_account.account_id = "account_id_value" - destinations.operating_account.account_type = "FLOODLIGHT_CONFIG" - destinations.product_destination_id = "product_destination_id_value" + destinations.operating_account.account_type = "GOOGLE_AD_MANAGER" audience_members = datamanager_v1.AudienceMember() audience_members.user_data.user_identifiers.email_address = "email_address_value" diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_async.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_async.py index f1f85560d7ef..508da2e4f32f 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_async.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_async.py @@ -41,9 +41,9 @@ async def sample_create_partner_link(): # Initialize request argument(s) partner_link = datamanager_v1.PartnerLink() partner_link.owning_account.account_id = "account_id_value" - partner_link.owning_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.owning_account.account_type = "GOOGLE_AD_MANAGER" partner_link.partner_account.account_id = "account_id_value" - partner_link.partner_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.partner_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.CreatePartnerLinkRequest( parent="parent_value", diff --git a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_sync.py b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_sync.py index 623f21b963cf..d092207937f6 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_sync.py +++ b/packages/google-ads-datamanager/samples/generated_samples/datamanager_v1_generated_partner_link_service_create_partner_link_sync.py @@ -41,9 +41,9 @@ def sample_create_partner_link(): # Initialize request argument(s) partner_link = datamanager_v1.PartnerLink() partner_link.owning_account.account_id = "account_id_value" - partner_link.owning_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.owning_account.account_type = "GOOGLE_AD_MANAGER" partner_link.partner_account.account_id = "account_id_value" - partner_link.partner_account.account_type = "FLOODLIGHT_CONFIG" + partner_link.partner_account.account_type = "GOOGLE_AD_MANAGER" request = datamanager_v1.CreatePartnerLinkRequest( parent="parent_value", diff --git a/packages/google-ads-datamanager/samples/generated_samples/snippet_metadata_google.ads.datamanager.v1.json b/packages/google-ads-datamanager/samples/generated_samples/snippet_metadata_google.ads.datamanager.v1.json index 47586343b863..0d7617f0e108 100644 --- a/packages/google-ads-datamanager/samples/generated_samples/snippet_metadata_google.ads.datamanager.v1.json +++ b/packages/google-ads-datamanager/samples/generated_samples/snippet_metadata_google.ads.datamanager.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-ads-datamanager", - "version": "0.9.2" + "version": "0.9.3" }, "snippets": [ { @@ -56,12 +56,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_IngestAdEvents_async", "segments": [ { - "end": 74, + "end": 67, "start": 27, "type": "FULL" }, { - "end": 74, + "end": 67, "start": 27, "type": "SHORT" }, @@ -71,18 +71,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 68, + "end": 61, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 71, - "start": 69, + "end": 64, + "start": 62, "type": "REQUEST_EXECUTION" }, { - "end": 75, - "start": 72, + "end": 68, + "start": 65, "type": "RESPONSE_HANDLING" } ], @@ -132,12 +132,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_IngestAdEvents_sync", "segments": [ { - "end": 74, + "end": 67, "start": 27, "type": "FULL" }, { - "end": 74, + "end": 67, "start": 27, "type": "SHORT" }, @@ -147,18 +147,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 68, + "end": 61, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 71, - "start": 69, + "end": 64, + "start": 62, "type": "REQUEST_EXECUTION" }, { - "end": 75, - "start": 72, + "end": 68, + "start": 65, "type": "RESPONSE_HANDLING" } ], @@ -209,12 +209,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_IngestAudienceMembers_async", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -224,18 +224,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 54, + "end": 53, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 55, + "end": 56, + "start": 54, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], @@ -285,12 +285,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_IngestAudienceMembers_sync", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -300,18 +300,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 54, + "end": 53, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 55, + "end": 56, + "start": 54, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], @@ -362,12 +362,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_IngestEvents_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -377,18 +377,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -438,12 +438,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_IngestEvents_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -453,18 +453,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -515,12 +515,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_RemoveAllAudienceMembers_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -530,18 +530,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -591,12 +591,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_RemoveAllAudienceMembers_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -606,18 +606,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -668,12 +668,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_RemoveAudienceMembers_async", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -683,18 +683,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 54, + "end": 53, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 55, + "end": 56, + "start": 54, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], @@ -744,12 +744,12 @@ "regionTag": "datamanager_v1_generated_IngestionService_RemoveAudienceMembers_sync", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -759,18 +759,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 54, + "end": 53, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 55, + "end": 56, + "start": 54, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-analytics-data/CHANGELOG.md b/packages/google-analytics-data/CHANGELOG.md index 486ff2aa311e..c9b0da9b787c 100644 --- a/packages/google-analytics-data/CHANGELOG.md +++ b/packages/google-analytics-data/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-analytics-data/#history +## [0.23.1](https://github.com/googleapis/google-cloud-python/compare/google-analytics-data-v0.23.0...google-analytics-data-v0.23.1) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.23.0](https://github.com/googleapis/google-cloud-python/compare/google-analytics-data-v0.22.0...google-analytics-data-v0.23.0) (2026-06-02) diff --git a/packages/google-analytics-data/google/analytics/data/gapic_version.py b/packages/google-analytics-data/google/analytics/data/gapic_version.py index 4d933124f35b..71c813b583aa 100644 --- a/packages/google-analytics-data/google/analytics/data/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.23.0" # {x-release-please-version} +__version__ = "0.23.1" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py index 4d933124f35b..71c813b583aa 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.23.0" # {x-release-please-version} +__version__ = "0.23.1" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py b/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py index 4d933124f35b..71c813b583aa 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.23.0" # {x-release-please-version} +__version__ = "0.23.1" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py b/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py index 1f14c92574e3..fac1b5156cfb 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py @@ -1359,6 +1359,9 @@ class ResponseMetaData(proto.Message): However if the results are not sampled, this field will not be defined. + data_truncation_reasons (MutableSequence[google.analytics.data_v1beta.types.ResponseMetaData.DataTruncationReason]): + If set, indicate there is data truncation in + the report. """ class SchemaRestrictionResponse(proto.Message): @@ -1410,6 +1413,134 @@ class ActiveMetricRestriction(proto.Message): message="ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction", ) + class DataTruncationReason(proto.Message): + r"""Describes a reason for data truncation in the report. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + data_truncation_type (google.analytics.data_v1beta.types.ResponseMetaData.DataTruncationReason.DataTruncationType): + The type of data truncation. + + This field is a member of `oneof`_ ``_data_truncation_type``. + data_truncation_message (str): + A descriptive message explaining the data + truncation. + + This field is a member of `oneof`_ ``_data_truncation_message``. + data_truncation_date (str): + The data truncation date in the format + YYYY-MM-DD. Indicates data before this date is + truncated. + + This field is a member of `oneof`_ ``_data_truncation_date``. + data_truncation_date_ranges (MutableSequence[google.analytics.data_v1beta.types.ResponseMetaData.DataTruncationReason.DataTruncationDateRange]): + The truncated date ranges. + """ + + class DataTruncationType(proto.Enum): + r"""The type of data truncation. + + Values: + DATA_TRUNCATION_TYPE_UNSPECIFIED (0): + Unspecified type. + DATA_TRUNCATION_TYPE_RULES_BASED_MODELS (1): + Data is truncated in attribution report for + rules-based models golden date. + DATA_TRUNCATION_TYPE_DATA_DRIVEN_ATTRIBUTION (2): + Data is truncated in attribution report for + data driven attribution golden date. + DATA_TRUNCATION_TYPE_DV360 (3): + Data is truncated because DV360 policy does + not permit data older than 2 years from being + returned. + DATA_TRUNCATION_TYPE_CM360 (4): + Data is truncated because CM360 policy does + not permit data older than 2 years from being + returned. + DATA_TRUNCATION_TYPE_ITEM_SCOPED_ECOMMERCE_METRICS (5): + New item-scoped ecommerce metrics only have + data after a specific date. + DATA_TRUNCATION_TYPE_EVENT_SCOPED_ECOMMERCE_METRICS (6): + New event-scoped ecommerce metrics only have + data after a specific date. + DATA_TRUNCATION_TYPE_DATE_RANGE (7): + Query date range may not be fully served. + DATA_TRUNCATION_TYPE_PROPERTY (8): + Data truncated because the query attempts to + read event data prior to its retention date. + DATA_TRUNCATION_TYPE_CONVERSIONS (9): + Data is truncated in conversions report. + DATA_TRUNCATION_TYPE_GOOGLE_ADS (10): + Data is truncated due to Google Ads 36 month + retention policy. + """ + + DATA_TRUNCATION_TYPE_UNSPECIFIED = 0 + DATA_TRUNCATION_TYPE_RULES_BASED_MODELS = 1 + DATA_TRUNCATION_TYPE_DATA_DRIVEN_ATTRIBUTION = 2 + DATA_TRUNCATION_TYPE_DV360 = 3 + DATA_TRUNCATION_TYPE_CM360 = 4 + DATA_TRUNCATION_TYPE_ITEM_SCOPED_ECOMMERCE_METRICS = 5 + DATA_TRUNCATION_TYPE_EVENT_SCOPED_ECOMMERCE_METRICS = 6 + DATA_TRUNCATION_TYPE_DATE_RANGE = 7 + DATA_TRUNCATION_TYPE_PROPERTY = 8 + DATA_TRUNCATION_TYPE_CONVERSIONS = 9 + DATA_TRUNCATION_TYPE_GOOGLE_ADS = 10 + + class DataTruncationDateRange(proto.Message): + r"""Define the truncated date range from start_date to end_date. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_date (str): + The start date in the format YYYY-MM-DD + (inclusive). + + This field is a member of `oneof`_ ``_start_date``. + end_date (str): + The end date in the format YYYY-MM-DD + (inclusive). + + This field is a member of `oneof`_ ``_end_date``. + """ + + start_date: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + end_date: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + data_truncation_type: "ResponseMetaData.DataTruncationReason.DataTruncationType" = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum="ResponseMetaData.DataTruncationReason.DataTruncationType", + ) + data_truncation_message: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + data_truncation_date: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + data_truncation_date_ranges: MutableSequence[ + "ResponseMetaData.DataTruncationReason.DataTruncationDateRange" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="ResponseMetaData.DataTruncationReason.DataTruncationDateRange", + ) + data_loss_from_other_row: bool = proto.Field( proto.BOOL, number=3, @@ -1445,6 +1576,13 @@ class ActiveMetricRestriction(proto.Message): number=9, message="SamplingMetadata", ) + data_truncation_reasons: MutableSequence[DataTruncationReason] = ( + proto.RepeatedField( + proto.MESSAGE, + number=10, + message=DataTruncationReason, + ) + ) class SamplingMetadata(proto.Message): diff --git a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json index 17e8af76d6de..9b97c5021543 100644 --- a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json +++ b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-data", - "version": "0.23.0" + "version": "0.23.1" }, "snippets": [ { diff --git a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json index c0d516e63f7d..f662e73082d6 100644 --- a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json +++ b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-data", - "version": "0.23.0" + "version": "0.23.1" }, "snippets": [ { diff --git a/packages/google-api-core/CHANGELOG.md b/packages/google-api-core/CHANGELOG.md index e138d6b5a306..2c41bdca86e2 100644 --- a/packages/google-api-core/CHANGELOG.md +++ b/packages/google-api-core/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-api-core/#history +## [2.38.0](https://github.com/googleapis/google-cloud-python/compare/google-api-core-v2.37.0...google-api-core-v2.38.0) (2026-09-17) + + +### Features + +* **core:** add request hook to enrich T4 network spans with GCP resource attributes (E) ([#18272](https://github.com/googleapis/google-cloud-python/issues/18272)) ([1ca95e9](https://github.com/googleapis/google-cloud-python/commit/1ca95e90199cf0a40077437a4c00f8039599dd5e)) + ## [2.37.0](https://github.com/googleapis/google-cloud-python/compare/google-api-core-v2.36.0...google-api-core-v2.37.0) (2026-09-14) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index f101cec28f5c..2d8c50acbfa9 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -18,6 +18,7 @@ from __future__ import annotations +import urllib.parse from typing import TYPE_CHECKING, Any, Callable, Sequence from google.api_core import _feature_gating_helpers @@ -25,7 +26,7 @@ if TYPE_CHECKING: # flake8: grpc, trace, and ClientInterceptor are imported only for static analysis and type annotations - # The `# noqa: F401` comment avoids flake8 "imported but not used" errors. + # The 'noqa: F401' comment avoids flake8 "imported but not used" errors. import grpc # noqa: F401 import opentelemetry.trace # noqa: F401 @@ -64,6 +65,141 @@ def is_otel_capabilities_enabled( return False +def _extract_endpoint_attributes( + client_options: ClientOptions | dict[str, Any] | None = None, +) -> dict[str, Any]: + """Extracts server.address, server.port (if non-default), and url.domain from client options if present. + + Args: + client_options: The client options object or dictionary. + + Returns: + dict[str, Any]: A dictionary containing url.domain and, if an api_endpoint is configured, + server.address and non-default server.port. + """ + attrs: dict[str, Any] = {} + endpoint = None + universe_domain = None + + if isinstance(client_options, dict): + endpoint = client_options.get("api_endpoint") + universe_domain = client_options.get("universe_domain") + elif client_options is not None: + endpoint = getattr(client_options, "api_endpoint", None) + universe_domain = getattr(client_options, "universe_domain", None) + + attrs["url.domain"] = universe_domain or "googleapis.com" + + if endpoint and isinstance(endpoint, str): + target = endpoint if "//" in endpoint else f"//{endpoint}" + parsed = None + hostname = None + port = None + try: + parsed = urllib.parse.urlsplit(target) + hostname = parsed.hostname + port = parsed.port + except ValueError: + pass + + if hostname: + attrs["server.address"] = hostname + if port and parsed: + scheme = parsed.scheme.lower() + is_default_port = (port == 443 and scheme in ("https", "")) or ( + port == 80 and scheme == "http" + ) + if not is_default_port: + attrs["server.port"] = port + return attrs + + +def _make_grpc_client_request_hook( + endpoint_attrs: dict[str, Any] | None = None, +) -> Callable[[Any, Any], None]: + """Creates an OpenTelemetry gRPC client request hook with optional endpoint attributes. + + Args: + endpoint_attrs: Optional static endpoint attributes to attach to every span. + + Returns: + Callable[[Any, Any], None]: The request hook callback. + """ + static_attrs = dict(endpoint_attrs) if endpoint_attrs else {} + + def client_request_hook(span: Any, request: Any) -> None: + if span is None or not getattr(span, "is_recording", lambda: True)(): + return + + # Upstream opentelemetry-instrumentation-grpc may format span names with a + # leading slash (e.g. "/package.Service/Method"). Normalize the span name + # and ensure rpc.method is always captured as the clean, fully-qualified name. + span_name = getattr(span, "name", None) + if isinstance(span_name, str) and span_name: + clean_method_name = span_name.lstrip("/") + if span_name.startswith("/") and hasattr(span, "update_name"): + span.update_name(clean_method_name) + span.set_attribute("rpc.method", clean_method_name) + + attrs: dict[str, Any] = { + "rpc.system.name": "grpc", + } + if static_attrs: + attrs.update(static_attrs) + for key, value in attrs.items(): + span.set_attribute(key, value) + + return client_request_hook + + +_grpc_client_request_hook = _make_grpc_client_request_hook() + + +def _grpc_client_response_hook(span: Any, response: Any) -> None: + """OpenTelemetry gRPC client response hook to record successful response status. + + Upstream ``opentelemetry-instrumentation-grpc`` sets the integer status code + ``rpc.grpc.status_code`` (e.g. 0), but does not record the modern string status + ``rpc.response.status_code`` (e.g. "OK") required by Cloud Trace and current + OpenTelemetry semantic conventions (v1.27.0+). + + This hook enriches successful RPC attempt spans with ``rpc.response.status_code = "OK"``. + Errors and non-OK statuses are handled at the Tier 3 method span layer or upstream. + + Upstream handles synchronous and asynchronous invocations differently: + - **Synchronous gRPC**: Upstream only invokes the response hook when an RPC call + succeeds. On failure, the hook is bypassed entirely. + - **Asynchronous gRPC**: Upstream invokes the response hook unconditionally for + both successes and failures (passing exception details on error). However, it + always marks ``span.status`` with an error status before calling the hook. + + Because of this disparity, this hook checks ``span.status`` to guard against + async failure callbacks while allowing synchronous and successful asynchronous + calls to be marked "OK". + + Note: + If upstream ``opentelemetry-instrumentation-grpc`` adds native support for + modern ``rpc.response.status_code`` in future releases, this hook can be retired. + + Args: + span: The OpenTelemetry span. + response: The gRPC response object or details. + """ + if not span.is_recording(): + return + + # Guard against upstream async calls that invoke this hook on failures. + status = getattr(span, "status", None) + status_code = getattr(status, "status_code", None) + if ( + getattr(status_code, "name", None) == "ERROR" + or getattr(status_code, "value", None) == 2 + ): + return + + span.set_attribute("rpc.response.status_code", "OK") + + def _get_tracer_provider( client_options: ClientOptions | dict[str, Any] | None = None, ) -> opentelemetry.trace.TracerProvider | None: @@ -101,8 +237,13 @@ def get_otel_interceptor( import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] + endpoint_attrs = _extract_endpoint_attributes(client_options) + request_hook = _make_grpc_client_request_hook(endpoint_attrs) + interceptor: ClientInterceptor = otel_grpc.client_interceptor( - tracer_provider=_get_tracer_provider(client_options) + tracer_provider=_get_tracer_provider(client_options), + request_hook=request_hook, + response_hook=_grpc_client_response_hook, ) def otel_interceptor(channel: grpc.Channel) -> grpc.Channel: @@ -130,6 +271,11 @@ def get_otel_async_interceptor( # Ignored by mypy: Optional dependency only loaded if early-return is skipped import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] + endpoint_attrs = _extract_endpoint_attributes(client_options) + request_hook = _make_grpc_client_request_hook(endpoint_attrs) + return otel_grpc.aio_client_interceptors( - tracer_provider=_get_tracer_provider(client_options) + tracer_provider=_get_tracer_provider(client_options), + request_hook=request_hook, + response_hook=_grpc_client_response_hook, ) diff --git a/packages/google-api-core/google/api_core/version.py b/packages/google-api-core/google/api_core/version.py index d69c6f259318..67494cad69f3 100644 --- a/packages/google-api-core/google/api_core/version.py +++ b/packages/google-api-core/google/api_core/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "2.37.0" +__version__ = "2.38.0" diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 8e8964e66264..4d7a0d283fd1 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -162,8 +162,15 @@ def test_get_otel_interceptor_enabled(monkeypatch): assert callable(interceptor) mock_otel_grpc.client_interceptor.assert_called_once_with( - tracer_provider=mock_tracer_provider + tracer_provider=mock_tracer_provider, + request_hook=mock.ANY, + response_hook=_observability._grpc_client_response_hook, ) + req_hook = mock_otel_grpc.client_interceptor.call_args[1]["request_hook"] + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call("url.domain", "googleapis.com") result = interceptor(mock_raw_channel) assert result is mock_wrapped_channel @@ -251,5 +258,287 @@ def test_get_otel_async_interceptor_enabled(monkeypatch): result = _observability.get_otel_async_interceptor(client_options=options) assert result is mock_async_interceptors mock_otel_grpc.aio_client_interceptors.assert_called_once_with( - tracer_provider=mock_tracer_provider + tracer_provider=mock_tracer_provider, + request_hook=mock.ANY, + response_hook=_observability._grpc_client_response_hook, ) + + req_hook = mock_otel_grpc.aio_client_interceptors.call_args[1]["request_hook"] + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call("url.domain", "googleapis.com") + + +@pytest.mark.parametrize( + "client_options,expected_attrs", + [ + (None, {"url.domain": "googleapis.com"}), + ({}, {"url.domain": "googleapis.com"}), + (ClientOptions(api_endpoint=None), {"url.domain": "googleapis.com"}), + ({"universe_domain": "myuniverse.com"}, {"url.domain": "myuniverse.com"}), + ( + ClientOptions(universe_domain="custom.domain"), + {"url.domain": "custom.domain"}, + ), + ( + {"api_endpoint": "secretmanager.googleapis.com"}, + { + "server.address": "secretmanager.googleapis.com", + "url.domain": "googleapis.com", + }, + ), + ( + {"api_endpoint": "secretmanager.googleapis.com:443"}, + { + "server.address": "secretmanager.googleapis.com", + "url.domain": "googleapis.com", + }, + ), + ( + {"api_endpoint": "https://secretmanager.googleapis.com:443"}, + { + "server.address": "secretmanager.googleapis.com", + "url.domain": "googleapis.com", + }, + ), + ( + {"api_endpoint": "http://localhost:80"}, + {"server.address": "localhost", "url.domain": "googleapis.com"}, + ), + ( + ClientOptions(api_endpoint="https://my-custom-host.com:8443/"), + { + "server.address": "my-custom-host.com", + "server.port": 8443, + "url.domain": "googleapis.com", + }, + ), + ( + ClientOptions(api_endpoint="http://[::1]:8080"), + { + "server.address": "::1", + "server.port": 8080, + "url.domain": "googleapis.com", + }, + ), + ( + ClientOptions(api_endpoint="http:///"), + {"url.domain": "googleapis.com"}, + ), + ( + ClientOptions(api_endpoint="example.com:not_a_port"), + {"server.address": "example.com", "url.domain": "googleapis.com"}, + ), + ( + ClientOptions(api_endpoint="http://[invalid:ipv6:80/"), + {"url.domain": "googleapis.com"}, + ), + ( + ClientOptions(api_endpoint="example.com:99999"), + {"server.address": "example.com", "url.domain": "googleapis.com"}, + ), + ], +) +def test_extract_endpoint_attributes(client_options, expected_attrs): + """Proves that _extract_endpoint_attributes correctly parses server.address, non-default server.port, and url.domain.""" + assert _observability._extract_endpoint_attributes(client_options) == expected_attrs + + +def test_grpc_client_request_hook(): + """Proves that _grpc_client_request_hook attaches extracted T4 attributes to recording spans, + normalizes span names, sets fully qualified rpc.method, and allows legacy rpc.system to coexist. + """ + # Non-recording span should not set attributes + mock_span_non_rec = mock.Mock() + mock_span_non_rec.is_recording.return_value = False + _observability._grpc_client_request_hook(mock_span_non_rec, mock.Mock()) + mock_span_non_rec.set_attribute.assert_not_called() + + # None span should safely return + _observability._grpc_client_request_hook(None, mock.Mock()) + + # Recording span with default hook, leading slash in span.name, and legacy rpc.system + mock_span_rec = mock.Mock() + mock_span_rec.is_recording.return_value = True + mock_span_rec.name = ( + "/google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + mock_span_rec._attributes = {"rpc.system": "grpc"} + + _observability._grpc_client_request_hook(mock_span_rec, mock.Mock()) + + # Verify span name normalized and rpc.method set to fully qualified name + mock_span_rec.update_name.assert_called_once_with( + "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + mock_span_rec.set_attribute.assert_any_call( + "rpc.method", "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + + # Verify rpc.system.name set and legacy rpc.system left intact + mock_span_rec.set_attribute.assert_any_call("rpc.system.name", "grpc") + assert mock_span_rec._attributes["rpc.system"] == "grpc" + + # Custom hook with endpoint attributes and already-clean span name (no leading slash) + endpoint_hook = _observability._make_grpc_client_request_hook( + {"server.address": "custom.api.com", "server.port": 443} + ) + mock_span_custom = mock.Mock() + mock_span_custom.is_recording.return_value = True + mock_span_custom.name = ( + "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + endpoint_hook(mock_span_custom, None) + mock_span_custom.set_attribute.assert_any_call("server.address", "custom.api.com") + mock_span_custom.set_attribute.assert_any_call("server.port", 443) + mock_span_custom.set_attribute.assert_any_call( + "rpc.method", "google.cloud.secretmanager.v1.SecretManagerService/ListSecrets" + ) + mock_span_custom.update_name.assert_not_called() + + +def test_grpc_client_request_hook_span_edge_cases(): + """Proves that _grpc_client_request_hook handles spans lacking update_name, + spans with None or non-string names, and empty string names gracefully. + """ + # 1. Leading slash in span.name but span lacks update_name + mock_span_no_update = mock.Mock(spec=["is_recording", "name", "set_attribute"]) + mock_span_no_update.is_recording.return_value = True + mock_span_no_update.name = "/package.Service/Method" + _observability._grpc_client_request_hook(mock_span_no_update, None) + mock_span_no_update.set_attribute.assert_any_call( + "rpc.method", "package.Service/Method" + ) + mock_span_no_update.set_attribute.assert_any_call("rpc.system.name", "grpc") + + # 2. Span with None name + mock_span_none_name = mock.Mock(spec=["is_recording", "name", "set_attribute"]) + mock_span_none_name.is_recording.return_value = True + mock_span_none_name.name = None + _observability._grpc_client_request_hook(mock_span_none_name, None) + mock_span_none_name.set_attribute.assert_any_call("rpc.system.name", "grpc") + assert not any( + call.args[0] == "rpc.method" + for call in mock_span_none_name.set_attribute.call_args_list + ) + + # 3. Span with empty string name + mock_span_empty_name = mock.Mock(spec=["is_recording", "name", "set_attribute"]) + mock_span_empty_name.is_recording.return_value = True + mock_span_empty_name.name = "" + _observability._grpc_client_request_hook(mock_span_empty_name, None) + mock_span_empty_name.set_attribute.assert_any_call("rpc.system.name", "grpc") + assert not any( + call.args[0] == "rpc.method" + for call in mock_span_empty_name.set_attribute.call_args_list + ) + + +def test_get_otel_interceptor_with_api_endpoint(monkeypatch): + """Proves that get_otel_interceptor injects server.address, server.port, and url.domain when api_endpoint is set.""" + monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") + options = ClientOptions( + api_endpoint="secretmanager.googleapis.com:8443", + universe_domain="custom-domain.com", + ) + + mock_otel = mock.Mock() + mock_otel_grpc = mock_otel.instrumentation.grpc + monkeypatch.setitem(sys.modules, "opentelemetry", mock_otel) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation", mock_otel.instrumentation + ) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation.grpc", mock_otel_grpc + ) + + interceptor = _observability.get_otel_interceptor(client_options=options) + assert callable(interceptor) + + # Verify custom request hook was passed + args, kwargs = mock_otel_grpc.client_interceptor.call_args + req_hook = kwargs["request_hook"] + assert req_hook is not _observability._grpc_client_request_hook + assert kwargs["response_hook"] is _observability._grpc_client_response_hook + + # Test invoking the custom hook + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call( + "server.address", "secretmanager.googleapis.com" + ) + mock_span.set_attribute.assert_any_call("server.port", 8443) + mock_span.set_attribute.assert_any_call("url.domain", "custom-domain.com") + + +def test_get_otel_async_interceptor_with_api_endpoint(monkeypatch): + """Proves that get_otel_async_interceptor injects server.address, server.port, and url.domain when api_endpoint is set.""" + monkeypatch.setenv("GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED", "true") + options = ClientOptions( + api_endpoint="secretmanager.googleapis.com:8443", + universe_domain="custom-domain.com", + ) + + mock_otel = mock.Mock() + mock_otel_grpc = mock_otel.instrumentation.grpc + monkeypatch.setitem(sys.modules, "opentelemetry", mock_otel) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation", mock_otel.instrumentation + ) + monkeypatch.setitem( + sys.modules, "opentelemetry.instrumentation.grpc", mock_otel_grpc + ) + + result = _observability.get_otel_async_interceptor(client_options=options) + assert result is not None + + args, kwargs = mock_otel_grpc.aio_client_interceptors.call_args + req_hook = kwargs["request_hook"] + assert req_hook is not _observability._grpc_client_request_hook + assert kwargs["response_hook"] is _observability._grpc_client_response_hook + + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + req_hook(mock_span, None) + mock_span.set_attribute.assert_any_call( + "server.address", "secretmanager.googleapis.com" + ) + mock_span.set_attribute.assert_any_call("server.port", 8443) + mock_span.set_attribute.assert_any_call("url.domain", "custom-domain.com") + + +def test_grpc_client_response_hook_success(): + """Proves that _grpc_client_response_hook sets rpc.response.status_code to 'OK' on success.""" + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_called_once_with("rpc.response.status_code", "OK") + + +def test_grpc_client_response_hook_not_recording(): + """Proves that _grpc_client_response_hook skips non-recording spans.""" + mock_span = mock.Mock() + mock_span.is_recording.return_value = False + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_not_called() + + +def test_grpc_client_response_hook_error_status(): + """Proves that _grpc_client_response_hook skips spans marked with ERROR status.""" + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + mock_span.status.status_code.name = "ERROR" + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_not_called() + + +def test_grpc_client_response_hook_error_status_value(): + """Proves that _grpc_client_response_hook skips spans with StatusCode.ERROR value (2).""" + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + mock_span.status.status_code.name = "UNKNOWN" + mock_span.status.status_code.value = 2 + _observability._grpc_client_response_hook(mock_span, mock.Mock()) + mock_span.set_attribute.assert_not_called() diff --git a/packages/google-apps-meet/.repo-metadata.json b/packages/google-apps-meet/.repo-metadata.json index d51f27f6028e..fa2ff9936594 100644 --- a/packages/google-apps-meet/.repo-metadata.json +++ b/packages/google-apps-meet/.repo-metadata.json @@ -10,7 +10,7 @@ "library_type": "GAPIC_AUTO", "name": "google-apps-meet", "name_pretty": "Google Meet", - "product_documentation": "https://developers.google.com/meet/api/guides/overview", + "product_documentation": "https://developers.google.com/workspace/meet/api/guides/overview", "release_level": "preview", "repo": "googleapis/google-cloud-python" } \ No newline at end of file diff --git a/packages/google-apps-meet/CHANGELOG.md b/packages/google-apps-meet/CHANGELOG.md index 24d8d955ecdf..ddd118ff6e1d 100644 --- a/packages/google-apps-meet/CHANGELOG.md +++ b/packages/google-apps-meet/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-apps-meet/#history +## [0.5.1](https://github.com/googleapis/google-cloud-python/compare/google-apps-meet-v0.5.0...google-apps-meet-v0.5.1) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.5.0](https://github.com/googleapis/google-cloud-python/compare/google-apps-meet-v0.4.0...google-apps-meet-v0.5.0) (2026-06-02) diff --git a/packages/google-apps-meet/README.rst b/packages/google-apps-meet/README.rst index 657fccf89b18..dd8aa5e51ffd 100644 --- a/packages/google-apps-meet/README.rst +++ b/packages/google-apps-meet/README.rst @@ -14,9 +14,9 @@ Python Client for Google Meet :target: https://pypi.org/project/google-apps-meet/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-apps-meet.svg :target: https://pypi.org/project/google-apps-meet/ -.. _Google Meet: https://developers.google.com/meet/api/guides/overview +.. _Google Meet: https://developers.google.com/workspace/meet/api/guides/overview .. _Client Library Documentation: https://googleapis.dev/python/google-apps-meet/latest -.. _Product Documentation: https://developers.google.com/meet/api/guides/overview +.. _Product Documentation: https://developers.google.com/workspace/meet/api/guides/overview Quick Start ----------- @@ -30,7 +30,7 @@ In order to use this library, you first need to go through the following steps: .. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project .. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Enable the Google Meet.: https://developers.google.com/meet/api/guides/overview +.. _Enable the Google Meet.: https://developers.google.com/workspace/meet/api/guides/overview .. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html Installation @@ -105,7 +105,7 @@ Next Steps - View this `README`_ to see the full list of Cloud APIs that we cover. -.. _Google Meet Product documentation: https://developers.google.com/meet/api/guides/overview +.. _Google Meet Product documentation: https://developers.google.com/workspace/meet/api/guides/overview .. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst Logging diff --git a/packages/google-apps-meet/docs/README.rst b/packages/google-apps-meet/docs/README.rst index 657fccf89b18..dd8aa5e51ffd 100644 --- a/packages/google-apps-meet/docs/README.rst +++ b/packages/google-apps-meet/docs/README.rst @@ -14,9 +14,9 @@ Python Client for Google Meet :target: https://pypi.org/project/google-apps-meet/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-apps-meet.svg :target: https://pypi.org/project/google-apps-meet/ -.. _Google Meet: https://developers.google.com/meet/api/guides/overview +.. _Google Meet: https://developers.google.com/workspace/meet/api/guides/overview .. _Client Library Documentation: https://googleapis.dev/python/google-apps-meet/latest -.. _Product Documentation: https://developers.google.com/meet/api/guides/overview +.. _Product Documentation: https://developers.google.com/workspace/meet/api/guides/overview Quick Start ----------- @@ -30,7 +30,7 @@ In order to use this library, you first need to go through the following steps: .. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project .. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Enable the Google Meet.: https://developers.google.com/meet/api/guides/overview +.. _Enable the Google Meet.: https://developers.google.com/workspace/meet/api/guides/overview .. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html Installation @@ -105,7 +105,7 @@ Next Steps - View this `README`_ to see the full list of Cloud APIs that we cover. -.. _Google Meet Product documentation: https://developers.google.com/meet/api/guides/overview +.. _Google Meet Product documentation: https://developers.google.com/workspace/meet/api/guides/overview .. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst Logging diff --git a/packages/google-apps-meet/docs/meet_v2/spaces_service.rst b/packages/google-apps-meet/docs/meet_v2/spaces_service.rst index b74b8555d371..f910bb514c95 100644 --- a/packages/google-apps-meet/docs/meet_v2/spaces_service.rst +++ b/packages/google-apps-meet/docs/meet_v2/spaces_service.rst @@ -4,3 +4,7 @@ SpacesService .. automodule:: google.apps.meet_v2.services.spaces_service :members: :inherited-members: + +.. automodule:: google.apps.meet_v2.services.spaces_service.pagers + :members: + :inherited-members: diff --git a/packages/google-apps-meet/google/apps/meet/__init__.py b/packages/google-apps-meet/google/apps/meet/__init__.py index bf1712d11fed..32db21500fa0 100644 --- a/packages/google-apps-meet/google/apps/meet/__init__.py +++ b/packages/google-apps-meet/google/apps/meet/__init__.py @@ -34,38 +34,51 @@ ConferenceRecord, DocsDestination, DriveDestination, + Member, Participant, ParticipantSession, PhoneUser, Recording, SignedinUser, + SmartNote, Space, SpaceConfig, Transcript, TranscriptEntry, ) from google.apps.meet_v2.types.service import ( + BatchUpdateMembersRequest, + BatchUpdateMembersResponse, + CreateMemberRequest, CreateSpaceRequest, + DeleteMemberRequest, EndActiveConferenceRequest, GetConferenceRecordRequest, + GetMemberRequest, GetParticipantRequest, GetParticipantSessionRequest, GetRecordingRequest, + GetSmartNoteRequest, GetSpaceRequest, GetTranscriptEntryRequest, GetTranscriptRequest, ListConferenceRecordsRequest, ListConferenceRecordsResponse, + ListMembersRequest, + ListMembersResponse, ListParticipantSessionsRequest, ListParticipantSessionsResponse, ListParticipantsRequest, ListParticipantsResponse, ListRecordingsRequest, ListRecordingsResponse, + ListSmartNotesRequest, + ListSmartNotesResponse, ListTranscriptEntriesRequest, ListTranscriptEntriesResponse, ListTranscriptsRequest, ListTranscriptsResponse, + UpdateMemberRequest, UpdateSpaceRequest, ) @@ -79,35 +92,48 @@ "ConferenceRecord", "DocsDestination", "DriveDestination", + "Member", "Participant", "ParticipantSession", "PhoneUser", "Recording", "SignedinUser", + "SmartNote", "Space", "SpaceConfig", "Transcript", "TranscriptEntry", + "BatchUpdateMembersRequest", + "BatchUpdateMembersResponse", + "CreateMemberRequest", "CreateSpaceRequest", + "DeleteMemberRequest", "EndActiveConferenceRequest", "GetConferenceRecordRequest", + "GetMemberRequest", "GetParticipantRequest", "GetParticipantSessionRequest", "GetRecordingRequest", + "GetSmartNoteRequest", "GetSpaceRequest", "GetTranscriptEntryRequest", "GetTranscriptRequest", "ListConferenceRecordsRequest", "ListConferenceRecordsResponse", + "ListMembersRequest", + "ListMembersResponse", "ListParticipantSessionsRequest", "ListParticipantSessionsResponse", "ListParticipantsRequest", "ListParticipantsResponse", "ListRecordingsRequest", "ListRecordingsResponse", + "ListSmartNotesRequest", + "ListSmartNotesResponse", "ListTranscriptEntriesRequest", "ListTranscriptEntriesResponse", "ListTranscriptsRequest", "ListTranscriptsResponse", + "UpdateMemberRequest", "UpdateSpaceRequest", ) diff --git a/packages/google-apps-meet/google/apps/meet/gapic_version.py b/packages/google-apps-meet/google/apps/meet/gapic_version.py index 7d9863d19611..acc458e7fa6f 100644 --- a/packages/google-apps-meet/google/apps/meet/gapic_version.py +++ b/packages/google-apps-meet/google/apps/meet/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.0" # {x-release-please-version} +__version__ = "0.5.1" # {x-release-please-version} diff --git a/packages/google-apps-meet/google/apps/meet_v2/__init__.py b/packages/google-apps-meet/google/apps/meet_v2/__init__.py index 4daae1c685f4..d57f95eae429 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/__init__.py +++ b/packages/google-apps-meet/google/apps/meet_v2/__init__.py @@ -44,38 +44,51 @@ ConferenceRecord, DocsDestination, DriveDestination, + Member, Participant, ParticipantSession, PhoneUser, Recording, SignedinUser, + SmartNote, Space, SpaceConfig, Transcript, TranscriptEntry, ) from .types.service import ( + BatchUpdateMembersRequest, + BatchUpdateMembersResponse, + CreateMemberRequest, CreateSpaceRequest, + DeleteMemberRequest, EndActiveConferenceRequest, GetConferenceRecordRequest, + GetMemberRequest, GetParticipantRequest, GetParticipantSessionRequest, GetRecordingRequest, + GetSmartNoteRequest, GetSpaceRequest, GetTranscriptEntryRequest, GetTranscriptRequest, ListConferenceRecordsRequest, ListConferenceRecordsResponse, + ListMembersRequest, + ListMembersResponse, ListParticipantSessionsRequest, ListParticipantSessionsResponse, ListParticipantsRequest, ListParticipantsResponse, ListRecordingsRequest, ListRecordingsResponse, + ListSmartNotesRequest, + ListSmartNotesResponse, ListTranscriptEntriesRequest, ListTranscriptEntriesResponse, ListTranscriptsRequest, ListTranscriptsResponse, + UpdateMemberRequest, UpdateSpaceRequest, ) @@ -84,41 +97,54 @@ "SpacesServiceAsyncClient", "ActiveConference", "AnonymousUser", + "BatchUpdateMembersRequest", + "BatchUpdateMembersResponse", "ConferenceRecord", "ConferenceRecordsServiceClient", + "CreateMemberRequest", "CreateSpaceRequest", + "DeleteMemberRequest", "DocsDestination", "DriveDestination", "EndActiveConferenceRequest", "GetConferenceRecordRequest", + "GetMemberRequest", "GetParticipantRequest", "GetParticipantSessionRequest", "GetRecordingRequest", + "GetSmartNoteRequest", "GetSpaceRequest", "GetTranscriptEntryRequest", "GetTranscriptRequest", "ListConferenceRecordsRequest", "ListConferenceRecordsResponse", + "ListMembersRequest", + "ListMembersResponse", "ListParticipantSessionsRequest", "ListParticipantSessionsResponse", "ListParticipantsRequest", "ListParticipantsResponse", "ListRecordingsRequest", "ListRecordingsResponse", + "ListSmartNotesRequest", + "ListSmartNotesResponse", "ListTranscriptEntriesRequest", "ListTranscriptEntriesResponse", "ListTranscriptsRequest", "ListTranscriptsResponse", + "Member", "Participant", "ParticipantSession", "PhoneUser", "Recording", "SignedinUser", + "SmartNote", "Space", "SpaceConfig", "SpacesServiceClient", "Transcript", "TranscriptEntry", + "UpdateMemberRequest", "UpdateSpaceRequest", ) diff --git a/packages/google-apps-meet/google/apps/meet_v2/gapic_metadata.json b/packages/google-apps-meet/google/apps/meet_v2/gapic_metadata.json index ec110267c3e4..34b385d63375 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/gapic_metadata.json +++ b/packages/google-apps-meet/google/apps/meet_v2/gapic_metadata.json @@ -30,6 +30,11 @@ "get_recording" ] }, + "GetSmartNote": { + "methods": [ + "get_smart_note" + ] + }, "GetTranscript": { "methods": [ "get_transcript" @@ -60,6 +65,11 @@ "list_recordings" ] }, + "ListSmartNotes": { + "methods": [ + "list_smart_notes" + ] + }, "ListTranscriptEntries": { "methods": [ "list_transcript_entries" @@ -95,6 +105,11 @@ "get_recording" ] }, + "GetSmartNote": { + "methods": [ + "get_smart_note" + ] + }, "GetTranscript": { "methods": [ "get_transcript" @@ -125,6 +140,11 @@ "list_recordings" ] }, + "ListSmartNotes": { + "methods": [ + "list_smart_notes" + ] + }, "ListTranscriptEntries": { "methods": [ "list_transcript_entries" @@ -160,6 +180,11 @@ "get_recording" ] }, + "GetSmartNote": { + "methods": [ + "get_smart_note" + ] + }, "GetTranscript": { "methods": [ "get_transcript" @@ -190,6 +215,11 @@ "list_recordings" ] }, + "ListSmartNotes": { + "methods": [ + "list_smart_notes" + ] + }, "ListTranscriptEntries": { "methods": [ "list_transcript_entries" @@ -209,21 +239,51 @@ "grpc": { "libraryClient": "SpacesServiceClient", "rpcs": { + "BatchUpdateMembers": { + "methods": [ + "batch_update_members" + ] + }, + "CreateMember": { + "methods": [ + "create_member" + ] + }, "CreateSpace": { "methods": [ "create_space" ] }, + "DeleteMember": { + "methods": [ + "delete_member" + ] + }, "EndActiveConference": { "methods": [ "end_active_conference" ] }, + "GetMember": { + "methods": [ + "get_member" + ] + }, "GetSpace": { "methods": [ "get_space" ] }, + "ListMembers": { + "methods": [ + "list_members" + ] + }, + "UpdateMember": { + "methods": [ + "update_member" + ] + }, "UpdateSpace": { "methods": [ "update_space" @@ -234,21 +294,51 @@ "grpc-async": { "libraryClient": "SpacesServiceAsyncClient", "rpcs": { + "BatchUpdateMembers": { + "methods": [ + "batch_update_members" + ] + }, + "CreateMember": { + "methods": [ + "create_member" + ] + }, "CreateSpace": { "methods": [ "create_space" ] }, + "DeleteMember": { + "methods": [ + "delete_member" + ] + }, "EndActiveConference": { "methods": [ "end_active_conference" ] }, + "GetMember": { + "methods": [ + "get_member" + ] + }, "GetSpace": { "methods": [ "get_space" ] }, + "ListMembers": { + "methods": [ + "list_members" + ] + }, + "UpdateMember": { + "methods": [ + "update_member" + ] + }, "UpdateSpace": { "methods": [ "update_space" @@ -259,21 +349,51 @@ "rest": { "libraryClient": "SpacesServiceClient", "rpcs": { + "BatchUpdateMembers": { + "methods": [ + "batch_update_members" + ] + }, + "CreateMember": { + "methods": [ + "create_member" + ] + }, "CreateSpace": { "methods": [ "create_space" ] }, + "DeleteMember": { + "methods": [ + "delete_member" + ] + }, "EndActiveConference": { "methods": [ "end_active_conference" ] }, + "GetMember": { + "methods": [ + "get_member" + ] + }, "GetSpace": { "methods": [ "get_space" ] }, + "ListMembers": { + "methods": [ + "list_members" + ] + }, + "UpdateMember": { + "methods": [ + "update_member" + ] + }, "UpdateSpace": { "methods": [ "update_space" diff --git a/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py b/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py index 7d9863d19611..acc458e7fa6f 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py +++ b/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.0" # {x-release-please-version} +__version__ = "0.5.1" # {x-release-please-version} diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/async_client.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/async_client.py index f6cd4732e341..1717cf27eee1 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/async_client.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/async_client.py @@ -97,6 +97,10 @@ class ConferenceRecordsServiceAsyncClient: parse_recording_path = staticmethod( ConferenceRecordsServiceClient.parse_recording_path ) + smart_note_path = staticmethod(ConferenceRecordsServiceClient.smart_note_path) + parse_smart_note_path = staticmethod( + ConferenceRecordsServiceClient.parse_smart_note_path + ) space_path = staticmethod(ConferenceRecordsServiceClient.space_path) parse_space_path = staticmethod(ConferenceRecordsServiceClient.parse_space_path) transcript_path = staticmethod(ConferenceRecordsServiceClient.transcript_path) @@ -1523,7 +1527,8 @@ async def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. .. code-block:: python @@ -1639,7 +1644,8 @@ async def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -1758,6 +1764,245 @@ async def sample_list_transcript_entries(): # Done; return the response. return response + async def get_smart_note( + self, + request: Optional[Union[service.GetSmartNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.SmartNote: + r"""Gets smart notes by smart note ID. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_get_smart_note(): + # Create a client + client = meet_v2.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_smart_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2.types.GetSmartNoteRequest, dict]]): + The request object. Request for GetSmartNote method. + name (:class:`str`): + Required. Resource name of the smart note. Format: + conferenceRecords/{conference_record}/smartNotes/{smart_note} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.SmartNote: + Metadata for a smart note generated + from a conference. It refers to the + notes generated from Take Notes with + Gemini during the conference. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetSmartNoteRequest): + request = service.GetSmartNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_smart_note + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_smart_notes( + self, + request: Optional[Union[service.ListSmartNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSmartNotesAsyncPager: + r"""Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_list_smart_notes(): + # Create a client + client = meet_v2.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2.types.ListSmartNotesRequest, dict]]): + The request object. Request for ListSmartNotes method. + parent (:class:`str`): + Required. Format: + ``conferenceRecords/{conference_record}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.services.conference_records_service.pagers.ListSmartNotesAsyncPager: + Response for ListSmartNotes method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListSmartNotesRequest): + request = service.ListSmartNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_smart_notes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSmartNotesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "ConferenceRecordsServiceAsyncClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py index c957d82f2986..031c69558265 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py @@ -250,6 +250,26 @@ def parse_recording_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def smart_note_path( + conference_record: str, + smart_note: str, + ) -> str: + """Returns a fully-qualified smart_note string.""" + return "conferenceRecords/{conference_record}/smartNotes/{smart_note}".format( + conference_record=conference_record, + smart_note=smart_note, + ) + + @staticmethod + def parse_smart_note_path(path: str) -> Dict[str, str]: + """Parses a smart_note path into its component segments.""" + m = re.match( + r"^conferenceRecords/(?P.+?)/smartNotes/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def space_path( space: str, @@ -1870,7 +1890,8 @@ def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. .. code-block:: python @@ -1983,7 +2004,8 @@ def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -2099,6 +2121,239 @@ def sample_list_transcript_entries(): # Done; return the response. return response + def get_smart_note( + self, + request: Optional[Union[service.GetSmartNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.SmartNote: + r"""Gets smart notes by smart note ID. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_get_smart_note(): + # Create a client + client = meet_v2.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_smart_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2.types.GetSmartNoteRequest, dict]): + The request object. Request for GetSmartNote method. + name (str): + Required. Resource name of the smart note. Format: + conferenceRecords/{conference_record}/smartNotes/{smart_note} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.SmartNote: + Metadata for a smart note generated + from a conference. It refers to the + notes generated from Take Notes with + Gemini during the conference. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetSmartNoteRequest): + request = service.GetSmartNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_smart_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_smart_notes( + self, + request: Optional[Union[service.ListSmartNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSmartNotesPager: + r"""Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_list_smart_notes(): + # Create a client + client = meet_v2.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.meet_v2.types.ListSmartNotesRequest, dict]): + The request object. Request for ListSmartNotes method. + parent (str): + Required. Format: + ``conferenceRecords/{conference_record}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.services.conference_records_service.pagers.ListSmartNotesPager: + Response for ListSmartNotes method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListSmartNotesRequest): + request = service.ListSmartNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_smart_notes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSmartNotesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ConferenceRecordsServiceClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/pagers.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/pagers.py index 52efb93415e7..ef980f682d18 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/pagers.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/pagers.py @@ -975,3 +975,159 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSmartNotesPager: + """A pager for iterating through ``list_smart_notes`` requests. + + This class thinly wraps an initial + :class:`google.apps.meet_v2.types.ListSmartNotesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``smart_notes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSmartNotes`` requests and continue to iterate + through the ``smart_notes`` field on the + corresponding responses. + + All the usual :class:`google.apps.meet_v2.types.ListSmartNotesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListSmartNotesResponse], + request: service.ListSmartNotesRequest, + response: service.ListSmartNotesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.meet_v2.types.ListSmartNotesRequest): + The initial request object. + response (google.apps.meet_v2.types.ListSmartNotesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListSmartNotesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListSmartNotesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resource.SmartNote]: + for page in self.pages: + yield from page.smart_notes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSmartNotesAsyncPager: + """A pager for iterating through ``list_smart_notes`` requests. + + This class thinly wraps an initial + :class:`google.apps.meet_v2.types.ListSmartNotesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``smart_notes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSmartNotes`` requests and continue to iterate + through the ``smart_notes`` field on the + corresponding responses. + + All the usual :class:`google.apps.meet_v2.types.ListSmartNotesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListSmartNotesResponse]], + request: service.ListSmartNotesRequest, + response: service.ListSmartNotesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.meet_v2.types.ListSmartNotesRequest): + The initial request object. + response (google.apps.meet_v2.types.ListSmartNotesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListSmartNotesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListSmartNotesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resource.SmartNote]: + async def async_generator(): + async for page in self.pages: + for response in page.smart_notes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/base.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/base.py index ef076f61fb56..a808748838e2 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/base.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/base.py @@ -311,6 +311,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_smart_note: gapic_v1.method.wrap_method( + self.get_smart_note, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_smart_notes: gapic_v1.method.wrap_method( + self.list_smart_notes, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), } def close(self): @@ -446,6 +474,26 @@ def list_transcript_entries( ]: raise NotImplementedError() + @property + def get_smart_note( + self, + ) -> Callable[ + [service.GetSmartNoteRequest], + Union[resource.SmartNote, Awaitable[resource.SmartNote]], + ]: + raise NotImplementedError() + + @property + def list_smart_notes( + self, + ) -> Callable[ + [service.ListSmartNotesRequest], + Union[ + service.ListSmartNotesResponse, Awaitable[service.ListSmartNotesResponse] + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc.py index f27cd63cdf79..6ad96539b6d2 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc.py @@ -614,7 +614,8 @@ def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. Returns: @@ -649,7 +650,8 @@ def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -671,6 +673,60 @@ def list_transcript_entries( ) return self._stubs["list_transcript_entries"] + @property + def get_smart_note( + self, + ) -> Callable[[service.GetSmartNoteRequest], resource.SmartNote]: + r"""Return a callable for the get smart note method over gRPC. + + Gets smart notes by smart note ID. + + Returns: + Callable[[~.GetSmartNoteRequest], + ~.SmartNote]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_smart_note" not in self._stubs: + self._stubs["get_smart_note"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.ConferenceRecordsService/GetSmartNote", + request_serializer=service.GetSmartNoteRequest.serialize, + response_deserializer=resource.SmartNote.deserialize, + ) + return self._stubs["get_smart_note"] + + @property + def list_smart_notes( + self, + ) -> Callable[[service.ListSmartNotesRequest], service.ListSmartNotesResponse]: + r"""Return a callable for the list smart notes method over gRPC. + + Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + Returns: + Callable[[~.ListSmartNotesRequest], + ~.ListSmartNotesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_smart_notes" not in self._stubs: + self._stubs["list_smart_notes"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.ConferenceRecordsService/ListSmartNotes", + request_serializer=service.ListSmartNotesRequest.serialize, + response_deserializer=service.ListSmartNotesResponse.deserialize, + ) + return self._stubs["list_smart_notes"] + def close(self): self._logged_channel.close() diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc_asyncio.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc_asyncio.py index 367e27aac1bc..0197f1f30786 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc_asyncio.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/grpc_asyncio.py @@ -635,7 +635,8 @@ def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. Returns: @@ -671,7 +672,8 @@ def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -693,6 +695,62 @@ def list_transcript_entries( ) return self._stubs["list_transcript_entries"] + @property + def get_smart_note( + self, + ) -> Callable[[service.GetSmartNoteRequest], Awaitable[resource.SmartNote]]: + r"""Return a callable for the get smart note method over gRPC. + + Gets smart notes by smart note ID. + + Returns: + Callable[[~.GetSmartNoteRequest], + Awaitable[~.SmartNote]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_smart_note" not in self._stubs: + self._stubs["get_smart_note"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.ConferenceRecordsService/GetSmartNote", + request_serializer=service.GetSmartNoteRequest.serialize, + response_deserializer=resource.SmartNote.deserialize, + ) + return self._stubs["get_smart_note"] + + @property + def list_smart_notes( + self, + ) -> Callable[ + [service.ListSmartNotesRequest], Awaitable[service.ListSmartNotesResponse] + ]: + r"""Return a callable for the list smart notes method over gRPC. + + Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + Returns: + Callable[[~.ListSmartNotesRequest], + Awaitable[~.ListSmartNotesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_smart_notes" not in self._stubs: + self._stubs["list_smart_notes"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.ConferenceRecordsService/ListSmartNotes", + request_serializer=service.ListSmartNotesRequest.serialize, + response_deserializer=service.ListSmartNotesResponse.deserialize, + ) + return self._stubs["list_smart_notes"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -864,6 +922,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_smart_note: self._wrap_method( + self.get_smart_note, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_smart_notes: self._wrap_method( + self.list_smart_notes, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest.py index d62d6a1f549b..86b90a5d3e15 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest.py @@ -104,6 +104,14 @@ def post_get_recording(self, response): logging.log(f"Received response: {response}") return response + def pre_get_smart_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_smart_note(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_transcript(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -152,6 +160,14 @@ def post_list_recordings(self, response): logging.log(f"Received response: {response}") return response + def pre_list_smart_notes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_smart_notes(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_transcript_entries(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -360,6 +376,50 @@ def post_get_recording_with_metadata( """ return response, metadata + def pre_get_smart_note( + self, + request: service.GetSmartNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetSmartNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_smart_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConferenceRecordsService server. + """ + return request, metadata + + def post_get_smart_note(self, response: resource.SmartNote) -> resource.SmartNote: + """Post-rpc interceptor for get_smart_note + + DEPRECATED. Please use the `post_get_smart_note_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ConferenceRecordsService server but before + it is returned to user code. This `post_get_smart_note` interceptor runs + before the `post_get_smart_note_with_metadata` interceptor. + """ + return response + + def post_get_smart_note_with_metadata( + self, + response: resource.SmartNote, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.SmartNote, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_smart_note + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ConferenceRecordsService server but before it is returned to user code. + + We recommend only using this `post_get_smart_note_with_metadata` + interceptor in new development instead of the `post_get_smart_note` interceptor. + When both interceptors are used, this `post_get_smart_note_with_metadata` interceptor runs after the + `post_get_smart_note` interceptor. The (possibly modified) response returned by + `post_get_smart_note` will be passed to + `post_get_smart_note_with_metadata`. + """ + return response, metadata + def pre_get_transcript( self, request: service.GetTranscriptRequest, @@ -648,6 +708,52 @@ def post_list_recordings_with_metadata( """ return response, metadata + def pre_list_smart_notes( + self, + request: service.ListSmartNotesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListSmartNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_smart_notes + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConferenceRecordsService server. + """ + return request, metadata + + def post_list_smart_notes( + self, response: service.ListSmartNotesResponse + ) -> service.ListSmartNotesResponse: + """Post-rpc interceptor for list_smart_notes + + DEPRECATED. Please use the `post_list_smart_notes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ConferenceRecordsService server but before + it is returned to user code. This `post_list_smart_notes` interceptor runs + before the `post_list_smart_notes_with_metadata` interceptor. + """ + return response + + def post_list_smart_notes_with_metadata( + self, + response: service.ListSmartNotesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListSmartNotesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_smart_notes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ConferenceRecordsService server but before it is returned to user code. + + We recommend only using this `post_list_smart_notes_with_metadata` + interceptor in new development instead of the `post_list_smart_notes` interceptor. + When both interceptors are used, this `post_list_smart_notes_with_metadata` interceptor runs after the + `post_list_smart_notes` interceptor. The (possibly modified) response returned by + `post_list_smart_notes` will be passed to + `post_list_smart_notes_with_metadata`. + """ + return response, metadata + def pre_list_transcript_entries( self, request: service.ListTranscriptEntriesRequest, @@ -1440,6 +1546,156 @@ def __call__( ) return resp + class _GetSmartNote( + _BaseConferenceRecordsServiceRestTransport._BaseGetSmartNote, + ConferenceRecordsServiceRestStub, + ): + def __hash__(self): + return hash("ConferenceRecordsServiceRestTransport.GetSmartNote") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetSmartNoteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.SmartNote: + r"""Call the get smart note method over HTTP. + + Args: + request (~.service.GetSmartNoteRequest): + The request object. Request for GetSmartNote method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resource.SmartNote: + Metadata for a smart note generated + from a conference. It refers to the + notes generated from Take Notes with + Gemini during the conference. + + """ + + http_options = _BaseConferenceRecordsServiceRestTransport._BaseGetSmartNote._get_http_options() + request, metadata = self._interceptor.pre_get_smart_note(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseConferenceRecordsServiceRestTransport._BaseGetSmartNote, + "_BaseGetSmartNote__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.ConferenceRecordsServiceClient.GetSmartNote", + extra={ + "serviceName": "google.apps.meet.v2.ConferenceRecordsService", + "rpcName": "GetSmartNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ConferenceRecordsServiceRestTransport._GetSmartNote._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.SmartNote() + pb_resp = resource.SmartNote.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_smart_note(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_smart_note_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.SmartNote.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2.ConferenceRecordsServiceClient.get_smart_note", + extra={ + "serviceName": "google.apps.meet.v2.ConferenceRecordsService", + "rpcName": "GetSmartNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetTranscript( _BaseConferenceRecordsServiceRestTransport._BaseGetTranscript, ConferenceRecordsServiceRestStub, @@ -2339,6 +2595,154 @@ def __call__( ) return resp + class _ListSmartNotes( + _BaseConferenceRecordsServiceRestTransport._BaseListSmartNotes, + ConferenceRecordsServiceRestStub, + ): + def __hash__(self): + return hash("ConferenceRecordsServiceRestTransport.ListSmartNotes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListSmartNotesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListSmartNotesResponse: + r"""Call the list smart notes method over HTTP. + + Args: + request (~.service.ListSmartNotesRequest): + The request object. Request for ListSmartNotes method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListSmartNotesResponse: + Response for ListSmartNotes method. + """ + + http_options = _BaseConferenceRecordsServiceRestTransport._BaseListSmartNotes._get_http_options() + request, metadata = self._interceptor.pre_list_smart_notes( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseConferenceRecordsServiceRestTransport._BaseListSmartNotes, + "_BaseListSmartNotes__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.ConferenceRecordsServiceClient.ListSmartNotes", + extra={ + "serviceName": "google.apps.meet.v2.ConferenceRecordsService", + "rpcName": "ListSmartNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ConferenceRecordsServiceRestTransport._ListSmartNotes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListSmartNotesResponse() + pb_resp = service.ListSmartNotesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_smart_notes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_smart_notes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListSmartNotesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2.ConferenceRecordsServiceClient.list_smart_notes", + extra={ + "serviceName": "google.apps.meet.v2.ConferenceRecordsService", + "rpcName": "ListSmartNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ListTranscriptEntries( _BaseConferenceRecordsServiceRestTransport._BaseListTranscriptEntries, ConferenceRecordsServiceRestStub, @@ -2670,6 +3074,14 @@ def get_recording( # In C++ this would require a dynamic_cast return self._GetRecording(self._session, self._host, self._interceptor) # type: ignore + @property + def get_smart_note( + self, + ) -> Callable[[service.GetSmartNoteRequest], resource.SmartNote]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSmartNote(self._session, self._host, self._interceptor) # type: ignore + @property def get_transcript( self, @@ -2725,6 +3137,14 @@ def list_recordings( # In C++ this would require a dynamic_cast return self._ListRecordings(self._session, self._host, self._interceptor) # type: ignore + @property + def list_smart_notes( + self, + ) -> Callable[[service.ListSmartNotesRequest], service.ListSmartNotesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSmartNotes(self._session, self._host, self._interceptor) # type: ignore + @property def list_transcript_entries( self, diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest_base.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest_base.py index 9f6fe355b5ac..047b2cc76906 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest_base.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/transports/rest_base.py @@ -151,6 +151,22 @@ def _get_http_options(): ] return http_options + class _BaseGetSmartNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=conferenceRecords/*/smartNotes/*}", + }, + ] + return http_options + class _BaseGetTranscript: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -245,6 +261,22 @@ def _get_http_options(): ] return http_options + class _BaseListSmartNotes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=conferenceRecords/*}/smartNotes", + }, + ] + return http_options + class _BaseListTranscriptEntries: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/async_client.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/async_client.py index 9d8921c6e49a..0d81f32c6a2e 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/async_client.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/async_client.py @@ -46,6 +46,7 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +from google.apps.meet_v2.services.spaces_service import pagers from google.apps.meet_v2.types import resource, service from .client import SpacesServiceClient @@ -78,6 +79,8 @@ class SpacesServiceAsyncClient: parse_conference_record_path = staticmethod( SpacesServiceClient.parse_conference_record_path ) + member_path = staticmethod(SpacesServiceClient.member_path) + parse_member_path = staticmethod(SpacesServiceClient.parse_member_path) space_path = staticmethod(SpacesServiceClient.space_path) parse_space_path = staticmethod(SpacesServiceClient.parse_space_path) common_billing_account_path = staticmethod( @@ -416,7 +419,7 @@ async def get_space( r"""Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. .. code-block:: python @@ -470,7 +473,7 @@ async def sample_get_space(): Meet `__. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -552,7 +555,7 @@ async def update_space( r"""Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. .. code-block:: python @@ -679,7 +682,7 @@ async def end_active_conference( r"""Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. .. code-block:: python @@ -718,7 +721,7 @@ async def sample_end_active_conference(): sensitive. For example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -777,6 +780,688 @@ async def sample_end_active_conference(): metadata=metadata, ) + async def create_member( + self, + request: Optional[Union[service.CreateMemberRequest, dict]] = None, + *, + parent: Optional[str] = None, + member: Optional[resource.Member] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Creates a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_create_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.CreateMemberRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_member(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2.types.CreateMemberRequest, dict]]): + The request object. Request to create a member for a + space. + parent (:class:`str`): + Required. Format: spaces/{space} + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + member (:class:`google.apps.meet_v2.types.Member`): + Required. The member to be created. + This corresponds to the ``member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, member] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateMemberRequest): + request = service.CreateMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if member is not None: + request.member = member + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_member( + self, + request: Optional[Union[service.GetMemberRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Gets a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_get_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.GetMemberRequest( + name="name_value", + ) + + # Make the request + response = await client.get_member(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2.types.GetMemberRequest, dict]]): + The request object. Request to get a member from a space. + name (:class:`str`): + Required. Format: + “spaces/{space}/members/{member}” + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetMemberRequest): + request = service.GetMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_members( + self, + request: Optional[Union[service.ListMembersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMembersAsyncPager: + r"""Lists members. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted this API response will + default to "name,email,role". + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_list_members(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.ListMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_members(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2.types.ListMembersRequest, dict]]): + The request object. Request to list all members of a + space. + parent (:class:`str`): + Required. Format: spaces/{space} + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.services.spaces_service.pagers.ListMembersAsyncPager: + Response of list members. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListMembersRequest): + request = service.ListMembersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_members + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMembersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_member( + self, + request: Optional[Union[service.DeleteMemberRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the member who was previously assigned roles + in the space. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_delete_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.DeleteMemberRequest( + name="name_value", + ) + + # Make the request + await client.delete_member(request=request) + + Args: + request (Optional[Union[google.apps.meet_v2.types.DeleteMemberRequest, dict]]): + The request object. Request to delete a member from a + space. + name (:class:`str`): + Required. Format: + “spaces/{space}/members/{member}” + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteMemberRequest): + request = service.DeleteMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_member( + self, + request: Optional[Union[service.UpdateMemberRequest, dict]] = None, + *, + member: Optional[resource.Member] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Updates a member. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_update_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.UpdateMemberRequest( + ) + + # Make the request + response = await client.update_member(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2.types.UpdateMemberRequest, dict]]): + The request object. Request to update a member. + member (:class:`google.apps.meet_v2.types.Member`): + Required. The Member to update. + Format: spaces/{space}/members/{member} + + This corresponds to the ``member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask used to specify the fields to be + updated in the member. If update_mask isn't provided(not + set, set with empty paths, or only has "" as paths), it + defaults to update all fields provided with values in + the request. Using "\*" as update_mask will update all + fields, including deleting fields not set in the + request. In case of BatchUpdate, it must be absent or + the same as the update_mask in BatchUpdateMembersRequest + when UpdateMemberRequest is built as a child request of + BatchUpdateMembersRequest. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [member, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMemberRequest): + request = service.UpdateMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if member is not None: + request.member = member + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("member.name", request.member.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_update_members( + self, + request: Optional[Union[service.BatchUpdateMembersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.BatchUpdateMembersResponse: + r"""Updates members of one space within a batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + async def sample_batch_update_members(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_update_members(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2.types.BatchUpdateMembersRequest, dict]]): + The request object. Request to update members of one + space within a batch. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.BatchUpdateMembersResponse: + Response of batch update members. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.BatchUpdateMembersRequest): + request = service.BatchUpdateMembersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_update_members + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "SpacesServiceAsyncClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py index 0b7846237a7a..f76ff4e30e12 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py @@ -70,6 +70,7 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +from google.apps.meet_v2.services.spaces_service import pagers from google.apps.meet_v2.types import resource, service from .transports.base import DEFAULT_CLIENT_INFO, SpacesServiceTransport @@ -185,6 +186,23 @@ def parse_conference_record_path(path: str) -> Dict[str, str]: m = re.match(r"^conferenceRecords/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def member_path( + space: str, + member: str, + ) -> str: + """Returns a fully-qualified member string.""" + return "spaces/{space}/members/{member}".format( + space=space, + member=member, + ) + + @staticmethod + def parse_member_path(path: str) -> Dict[str, str]: + """Parses a member path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/members/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def space_path( space: str, @@ -714,7 +732,7 @@ def get_space( r"""Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. .. code-block:: python @@ -768,7 +786,7 @@ def sample_get_space(): Meet `__. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -847,7 +865,7 @@ def update_space( r"""Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. .. code-block:: python @@ -971,7 +989,7 @@ def end_active_conference( r"""Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. .. code-block:: python @@ -1010,7 +1028,7 @@ def sample_end_active_conference(): sensitive. For example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1066,6 +1084,671 @@ def sample_end_active_conference(): metadata=metadata, ) + def create_member( + self, + request: Optional[Union[service.CreateMemberRequest, dict]] = None, + *, + parent: Optional[str] = None, + member: Optional[resource.Member] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Creates a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_create_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.CreateMemberRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_member(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2.types.CreateMemberRequest, dict]): + The request object. Request to create a member for a + space. + parent (str): + Required. Format: spaces/{space} + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + member (google.apps.meet_v2.types.Member): + Required. The member to be created. + This corresponds to the ``member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, member] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateMemberRequest): + request = service.CreateMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if member is not None: + request.member = member + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_member( + self, + request: Optional[Union[service.GetMemberRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Gets a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_get_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.GetMemberRequest( + name="name_value", + ) + + # Make the request + response = client.get_member(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2.types.GetMemberRequest, dict]): + The request object. Request to get a member from a space. + name (str): + Required. Format: + “spaces/{space}/members/{member}” + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetMemberRequest): + request = service.GetMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_members( + self, + request: Optional[Union[service.ListMembersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMembersPager: + r"""Lists members. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted this API response will + default to "name,email,role". + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_list_members(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.ListMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_members(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.meet_v2.types.ListMembersRequest, dict]): + The request object. Request to list all members of a + space. + parent (str): + Required. Format: spaces/{space} + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.services.spaces_service.pagers.ListMembersPager: + Response of list members. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListMembersRequest): + request = service.ListMembersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_members] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMembersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_member( + self, + request: Optional[Union[service.DeleteMemberRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the member who was previously assigned roles + in the space. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_delete_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.DeleteMemberRequest( + name="name_value", + ) + + # Make the request + client.delete_member(request=request) + + Args: + request (Union[google.apps.meet_v2.types.DeleteMemberRequest, dict]): + The request object. Request to delete a member from a + space. + name (str): + Required. Format: + “spaces/{space}/members/{member}” + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteMemberRequest): + request = service.DeleteMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_member( + self, + request: Optional[Union[service.UpdateMemberRequest, dict]] = None, + *, + member: Optional[resource.Member] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Updates a member. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_update_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.UpdateMemberRequest( + ) + + # Make the request + response = client.update_member(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2.types.UpdateMemberRequest, dict]): + The request object. Request to update a member. + member (google.apps.meet_v2.types.Member): + Required. The Member to update. + Format: spaces/{space}/members/{member} + + This corresponds to the ``member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask used to specify the fields to be + updated in the member. If update_mask isn't provided(not + set, set with empty paths, or only has "" as paths), it + defaults to update all fields provided with values in + the request. Using "\*" as update_mask will update all + fields, including deleting fields not set in the + request. In case of BatchUpdate, it must be absent or + the same as the update_mask in BatchUpdateMembersRequest + when UpdateMemberRequest is built as a child request of + BatchUpdateMembersRequest. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [member, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMemberRequest): + request = service.UpdateMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if member is not None: + request.member = member + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("member.name", request.member.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_members( + self, + request: Optional[Union[service.BatchUpdateMembersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.BatchUpdateMembersResponse: + r"""Updates members of one space within a batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2 + + def sample_batch_update_members(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_members(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2.types.BatchUpdateMembersRequest, dict]): + The request object. Request to update members of one + space within a batch. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2.types.BatchUpdateMembersResponse: + Response of batch update members. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.BatchUpdateMembersRequest): + request = service.BatchUpdateMembersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_members] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "SpacesServiceClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/pagers.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/pagers.py new file mode 100644 index 000000000000..2d0eba8db704 --- /dev/null +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.apps.meet_v2.types import resource, service + + +class ListMembersPager: + """A pager for iterating through ``list_members`` requests. + + This class thinly wraps an initial + :class:`google.apps.meet_v2.types.ListMembersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``members`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMembers`` requests and continue to iterate + through the ``members`` field on the + corresponding responses. + + All the usual :class:`google.apps.meet_v2.types.ListMembersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListMembersResponse], + request: service.ListMembersRequest, + response: service.ListMembersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.meet_v2.types.ListMembersRequest): + The initial request object. + response (google.apps.meet_v2.types.ListMembersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListMembersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListMembersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resource.Member]: + for page in self.pages: + yield from page.members + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMembersAsyncPager: + """A pager for iterating through ``list_members`` requests. + + This class thinly wraps an initial + :class:`google.apps.meet_v2.types.ListMembersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``members`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMembers`` requests and continue to iterate + through the ``members`` field on the + corresponding responses. + + All the usual :class:`google.apps.meet_v2.types.ListMembersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListMembersResponse]], + request: service.ListMembersRequest, + response: service.ListMembersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.meet_v2.types.ListMembersRequest): + The initial request object. + response (google.apps.meet_v2.types.ListMembersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListMembersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListMembersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resource.Member]: + async def async_generator(): + async for page in self.pages: + for response in page.members: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/base.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/base.py index 88d64d03fcf1..58c37353fbe2 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/base.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/base.py @@ -174,6 +174,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_member: gapic_v1.method.wrap_method( + self.create_member, + default_timeout=80.0, + client_info=client_info, + ), + self.get_member: gapic_v1.method.wrap_method( + self.get_member, + default_timeout=60.0, + client_info=client_info, + ), + self.list_members: gapic_v1.method.wrap_method( + self.list_members, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_member: gapic_v1.method.wrap_method( + self.delete_member, + default_timeout=60.0, + client_info=client_info, + ), + self.update_member: gapic_v1.method.wrap_method( + self.update_member, + default_timeout=60.0, + client_info=client_info, + ), + self.batch_update_members: gapic_v1.method.wrap_method( + self.batch_update_members, + default_timeout=60.0, + client_info=client_info, + ), } def close(self): @@ -218,6 +248,62 @@ def end_active_conference( ]: raise NotImplementedError() + @property + def create_member( + self, + ) -> Callable[ + [service.CreateMemberRequest], + Union[resource.Member, Awaitable[resource.Member]], + ]: + raise NotImplementedError() + + @property + def get_member( + self, + ) -> Callable[ + [service.GetMemberRequest], Union[resource.Member, Awaitable[resource.Member]] + ]: + raise NotImplementedError() + + @property + def list_members( + self, + ) -> Callable[ + [service.ListMembersRequest], + Union[service.ListMembersResponse, Awaitable[service.ListMembersResponse]], + ]: + raise NotImplementedError() + + @property + def delete_member( + self, + ) -> Callable[ + [service.DeleteMemberRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def update_member( + self, + ) -> Callable[ + [service.UpdateMemberRequest], + Union[resource.Member, Awaitable[resource.Member]], + ]: + raise NotImplementedError() + + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], + Union[ + service.BatchUpdateMembersResponse, + Awaitable[service.BatchUpdateMembersResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc.py index 5f1fd2ea5221..0bb60666a39a 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc.py @@ -357,7 +357,7 @@ def get_space(self) -> Callable[[service.GetSpaceRequest], resource.Space]: Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. Returns: Callable[[~.GetSpaceRequest], @@ -384,7 +384,7 @@ def update_space(self) -> Callable[[service.UpdateSpaceRequest], resource.Space] Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. Returns: Callable[[~.UpdateSpaceRequest], @@ -413,7 +413,7 @@ def end_active_conference( Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. Returns: Callable[[~.EndActiveConferenceRequest], @@ -433,6 +433,172 @@ def end_active_conference( ) return self._stubs["end_active_conference"] + @property + def create_member(self) -> Callable[[service.CreateMemberRequest], resource.Member]: + r"""Return a callable for the create member method over gRPC. + + Creates a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + Returns: + Callable[[~.CreateMemberRequest], + ~.Member]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_member" not in self._stubs: + self._stubs["create_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/CreateMember", + request_serializer=service.CreateMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["create_member"] + + @property + def get_member(self) -> Callable[[service.GetMemberRequest], resource.Member]: + r"""Return a callable for the get member method over gRPC. + + Gets a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + Returns: + Callable[[~.GetMemberRequest], + ~.Member]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_member" not in self._stubs: + self._stubs["get_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/GetMember", + request_serializer=service.GetMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["get_member"] + + @property + def list_members( + self, + ) -> Callable[[service.ListMembersRequest], service.ListMembersResponse]: + r"""Return a callable for the list members method over gRPC. + + Lists members. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted this API response will + default to "name,email,role". + + Returns: + Callable[[~.ListMembersRequest], + ~.ListMembersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_members" not in self._stubs: + self._stubs["list_members"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/ListMembers", + request_serializer=service.ListMembersRequest.serialize, + response_deserializer=service.ListMembersResponse.deserialize, + ) + return self._stubs["list_members"] + + @property + def delete_member(self) -> Callable[[service.DeleteMemberRequest], empty_pb2.Empty]: + r"""Return a callable for the delete member method over gRPC. + + Deletes the member who was previously assigned roles + in the space. + + Returns: + Callable[[~.DeleteMemberRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_member" not in self._stubs: + self._stubs["delete_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/DeleteMember", + request_serializer=service.DeleteMemberRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_member"] + + @property + def update_member(self) -> Callable[[service.UpdateMemberRequest], resource.Member]: + r"""Return a callable for the update member method over gRPC. + + Updates a member. + + Returns: + Callable[[~.UpdateMemberRequest], + ~.Member]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_member" not in self._stubs: + self._stubs["update_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/UpdateMember", + request_serializer=service.UpdateMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["update_member"] + + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], service.BatchUpdateMembersResponse + ]: + r"""Return a callable for the batch update members method over gRPC. + + Updates members of one space within a batch. + + Returns: + Callable[[~.BatchUpdateMembersRequest], + ~.BatchUpdateMembersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_members" not in self._stubs: + self._stubs["batch_update_members"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/BatchUpdateMembers", + request_serializer=service.BatchUpdateMembersRequest.serialize, + response_deserializer=service.BatchUpdateMembersResponse.deserialize, + ) + return self._stubs["batch_update_members"] + def close(self): self._logged_channel.close() diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc_asyncio.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc_asyncio.py index c5b5e2d158ea..523b50e54528 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc_asyncio.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/grpc_asyncio.py @@ -369,7 +369,7 @@ def get_space( Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. Returns: Callable[[~.GetSpaceRequest], @@ -398,7 +398,7 @@ def update_space( Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. Returns: Callable[[~.UpdateSpaceRequest], @@ -427,7 +427,7 @@ def end_active_conference( Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. Returns: Callable[[~.EndActiveConferenceRequest], @@ -447,6 +447,181 @@ def end_active_conference( ) return self._stubs["end_active_conference"] + @property + def create_member( + self, + ) -> Callable[[service.CreateMemberRequest], Awaitable[resource.Member]]: + r"""Return a callable for the create member method over gRPC. + + Creates a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + Returns: + Callable[[~.CreateMemberRequest], + Awaitable[~.Member]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_member" not in self._stubs: + self._stubs["create_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/CreateMember", + request_serializer=service.CreateMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["create_member"] + + @property + def get_member( + self, + ) -> Callable[[service.GetMemberRequest], Awaitable[resource.Member]]: + r"""Return a callable for the get member method over gRPC. + + Gets a member. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted, this API response will + default to "name,email,role". + + Returns: + Callable[[~.GetMemberRequest], + Awaitable[~.Member]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_member" not in self._stubs: + self._stubs["get_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/GetMember", + request_serializer=service.GetMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["get_member"] + + @property + def list_members( + self, + ) -> Callable[[service.ListMembersRequest], Awaitable[service.ListMembersResponse]]: + r"""Return a callable for the list members method over gRPC. + + Lists members. + + This API supports the ``fields`` parameter in + `SystemParameterContext `__. + When the ``fields`` parameter is omitted this API response will + default to "name,email,role". + + Returns: + Callable[[~.ListMembersRequest], + Awaitable[~.ListMembersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_members" not in self._stubs: + self._stubs["list_members"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/ListMembers", + request_serializer=service.ListMembersRequest.serialize, + response_deserializer=service.ListMembersResponse.deserialize, + ) + return self._stubs["list_members"] + + @property + def delete_member( + self, + ) -> Callable[[service.DeleteMemberRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete member method over gRPC. + + Deletes the member who was previously assigned roles + in the space. + + Returns: + Callable[[~.DeleteMemberRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_member" not in self._stubs: + self._stubs["delete_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/DeleteMember", + request_serializer=service.DeleteMemberRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_member"] + + @property + def update_member( + self, + ) -> Callable[[service.UpdateMemberRequest], Awaitable[resource.Member]]: + r"""Return a callable for the update member method over gRPC. + + Updates a member. + + Returns: + Callable[[~.UpdateMemberRequest], + Awaitable[~.Member]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_member" not in self._stubs: + self._stubs["update_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/UpdateMember", + request_serializer=service.UpdateMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["update_member"] + + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], + Awaitable[service.BatchUpdateMembersResponse], + ]: + r"""Return a callable for the batch update members method over gRPC. + + Updates members of one space within a batch. + + Returns: + Callable[[~.BatchUpdateMembersRequest], + Awaitable[~.BatchUpdateMembersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_members" not in self._stubs: + self._stubs["batch_update_members"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2.SpacesService/BatchUpdateMembers", + request_serializer=service.BatchUpdateMembersRequest.serialize, + response_deserializer=service.BatchUpdateMembersResponse.deserialize, + ) + return self._stubs["batch_update_members"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -479,6 +654,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_member: self._wrap_method( + self.create_member, + default_timeout=80.0, + client_info=client_info, + ), + self.get_member: self._wrap_method( + self.get_member, + default_timeout=60.0, + client_info=client_info, + ), + self.list_members: self._wrap_method( + self.list_members, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_member: self._wrap_method( + self.delete_member, + default_timeout=60.0, + client_info=client_info, + ), + self.update_member: self._wrap_method( + self.update_member, + default_timeout=60.0, + client_info=client_info, + ), + self.batch_update_members: self._wrap_method( + self.batch_update_members, + default_timeout=60.0, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest.py index 296df23eb005..37b55f1bd54f 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest.py @@ -73,6 +73,22 @@ class SpacesServiceRestInterceptor: .. code-block:: python class MyCustomSpacesServiceInterceptor(SpacesServiceRestInterceptor): + def pre_batch_update_members(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_members(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_member(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_space(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -81,10 +97,22 @@ def post_create_space(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_end_active_conference(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_get_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_member(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_space(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -93,6 +121,22 @@ def post_get_space(self, response): logging.log(f"Received response: {response}") return response + def pre_list_members(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_members(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_member(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_space(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -107,6 +151,100 @@ def post_update_space(self, response): """ + def pre_batch_update_members( + self, + request: service.BatchUpdateMembersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.BatchUpdateMembersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for batch_update_members + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + + def post_batch_update_members( + self, response: service.BatchUpdateMembersResponse + ) -> service.BatchUpdateMembersResponse: + """Post-rpc interceptor for batch_update_members + + DEPRECATED. Please use the `post_batch_update_members_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SpacesService server but before + it is returned to user code. This `post_batch_update_members` interceptor runs + before the `post_batch_update_members_with_metadata` interceptor. + """ + return response + + def post_batch_update_members_with_metadata( + self, + response: service.BatchUpdateMembersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.BatchUpdateMembersResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for batch_update_members + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SpacesService server but before it is returned to user code. + + We recommend only using this `post_batch_update_members_with_metadata` + interceptor in new development instead of the `post_batch_update_members` interceptor. + When both interceptors are used, this `post_batch_update_members_with_metadata` interceptor runs after the + `post_batch_update_members` interceptor. The (possibly modified) response returned by + `post_batch_update_members` will be passed to + `post_batch_update_members_with_metadata`. + """ + return response, metadata + + def pre_create_member( + self, + request: service.CreateMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.CreateMemberRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + + def post_create_member(self, response: resource.Member) -> resource.Member: + """Post-rpc interceptor for create_member + + DEPRECATED. Please use the `post_create_member_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SpacesService server but before + it is returned to user code. This `post_create_member` interceptor runs + before the `post_create_member_with_metadata` interceptor. + """ + return response + + def post_create_member_with_metadata( + self, + response: resource.Member, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.Member, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_member + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SpacesService server but before it is returned to user code. + + We recommend only using this `post_create_member_with_metadata` + interceptor in new development instead of the `post_create_member` interceptor. + When both interceptors are used, this `post_create_member_with_metadata` interceptor runs after the + `post_create_member` interceptor. The (possibly modified) response returned by + `post_create_member` will be passed to + `post_create_member_with_metadata`. + """ + return response, metadata + def pre_create_space( self, request: service.CreateSpaceRequest, @@ -151,6 +289,18 @@ def post_create_space_with_metadata( """ return response, metadata + def pre_delete_member( + self, + request: service.DeleteMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.DeleteMemberRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + def pre_end_active_conference( self, request: service.EndActiveConferenceRequest, @@ -165,6 +315,50 @@ def pre_end_active_conference( """ return request, metadata + def pre_get_member( + self, + request: service.GetMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetMemberRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + + def post_get_member(self, response: resource.Member) -> resource.Member: + """Post-rpc interceptor for get_member + + DEPRECATED. Please use the `post_get_member_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SpacesService server but before + it is returned to user code. This `post_get_member` interceptor runs + before the `post_get_member_with_metadata` interceptor. + """ + return response + + def post_get_member_with_metadata( + self, + response: resource.Member, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.Member, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_member + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SpacesService server but before it is returned to user code. + + We recommend only using this `post_get_member_with_metadata` + interceptor in new development instead of the `post_get_member` interceptor. + When both interceptors are used, this `post_get_member_with_metadata` interceptor runs after the + `post_get_member` interceptor. The (possibly modified) response returned by + `post_get_member` will be passed to + `post_get_member_with_metadata`. + """ + return response, metadata + def pre_get_space( self, request: service.GetSpaceRequest, @@ -209,6 +403,96 @@ def post_get_space_with_metadata( """ return response, metadata + def pre_list_members( + self, + request: service.ListMembersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListMembersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_members + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + + def post_list_members( + self, response: service.ListMembersResponse + ) -> service.ListMembersResponse: + """Post-rpc interceptor for list_members + + DEPRECATED. Please use the `post_list_members_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SpacesService server but before + it is returned to user code. This `post_list_members` interceptor runs + before the `post_list_members_with_metadata` interceptor. + """ + return response + + def post_list_members_with_metadata( + self, + response: service.ListMembersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListMembersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_members + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SpacesService server but before it is returned to user code. + + We recommend only using this `post_list_members_with_metadata` + interceptor in new development instead of the `post_list_members` interceptor. + When both interceptors are used, this `post_list_members_with_metadata` interceptor runs after the + `post_list_members` interceptor. The (possibly modified) response returned by + `post_list_members` will be passed to + `post_list_members_with_metadata`. + """ + return response, metadata + + def pre_update_member( + self, + request: service.UpdateMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.UpdateMemberRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + + def post_update_member(self, response: resource.Member) -> resource.Member: + """Post-rpc interceptor for update_member + + DEPRECATED. Please use the `post_update_member_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SpacesService server but before + it is returned to user code. This `post_update_member` interceptor runs + before the `post_update_member_with_metadata` interceptor. + """ + return response + + def post_update_member_with_metadata( + self, + response: resource.Member, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.Member, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_member + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SpacesService server but before it is returned to user code. + + We recommend only using this `post_update_member_with_metadata` + interceptor in new development instead of the `post_update_member` interceptor. + When both interceptors are used, this `post_update_member_with_metadata` interceptor runs after the + `post_update_member` interceptor. The (possibly modified) response returned by + `post_update_member` will be passed to + `post_update_member_with_metadata`. + """ + return response, metadata + def pre_update_space( self, request: service.UpdateSpaceRequest, @@ -347,11 +631,11 @@ def __init__( self._interceptor = interceptor or SpacesServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateSpace( - _BaseSpacesServiceRestTransport._BaseCreateSpace, SpacesServiceRestStub + class _BatchUpdateMembers( + _BaseSpacesServiceRestTransport._BaseBatchUpdateMembers, SpacesServiceRestStub ): def __hash__(self): - return hash("SpacesServiceRestTransport.CreateSpace") + return hash("SpacesServiceRestTransport.BatchUpdateMembers") @staticmethod def _get_response( @@ -378,17 +662,18 @@ def _get_response( def __call__( self, - request: service.CreateSpaceRequest, + request: service.BatchUpdateMembersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resource.Space: - r"""Call the create space method over HTTP. + ) -> service.BatchUpdateMembersResponse: + r"""Call the batch update members method over HTTP. Args: - request (~.service.CreateSpaceRequest): - The request object. Request to create a space. + request (~.service.BatchUpdateMembersRequest): + The request object. Request to update members of one + space within a batch. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -398,23 +683,20 @@ def __call__( be of type `bytes`. Returns: - ~.resource.Space: - Virtual place where conferences are - held. Only one active conference can be - held in one space at any given time. - + ~.service.BatchUpdateMembersResponse: + Response of batch update members. """ - http_options = ( - _BaseSpacesServiceRestTransport._BaseCreateSpace._get_http_options() + http_options = _BaseSpacesServiceRestTransport._BaseBatchUpdateMembers._get_http_options() + request, metadata = self._interceptor.pre_batch_update_members( + request, metadata ) - request, metadata = self._interceptor.pre_create_space(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseSpacesServiceRestTransport._BaseCreateSpace, - "_BaseCreateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseSpacesServiceRestTransport._BaseBatchUpdateMembers, + "_BaseBatchUpdateMembers__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -438,17 +720,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.apps.meet_v2.SpacesServiceClient.CreateSpace", + f"Sending request for google.apps.meet_v2.SpacesServiceClient.BatchUpdateMembers", extra={ "serviceName": "google.apps.meet.v2.SpacesService", - "rpcName": "CreateSpace", + "rpcName": "BatchUpdateMembers", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = SpacesServiceRestTransport._CreateSpace._get_response( + response = SpacesServiceRestTransport._BatchUpdateMembers._get_response( self._host, metadata, query_params, @@ -464,21 +746,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resource.Space() - pb_resp = resource.Space.pb(resp) + resp = service.BatchUpdateMembersResponse() + pb_resp = service.BatchUpdateMembersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_space(resp) + resp = self._interceptor.post_batch_update_members(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_space_with_metadata( + resp, _ = self._interceptor.post_batch_update_members_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resource.Space.to_json(response) + response_payload = service.BatchUpdateMembersResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -487,21 +771,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.apps.meet_v2.SpacesServiceClient.create_space", + "Received response for google.apps.meet_v2.SpacesServiceClient.batch_update_members", extra={ "serviceName": "google.apps.meet.v2.SpacesService", - "rpcName": "CreateSpace", + "rpcName": "BatchUpdateMembers", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _EndActiveConference( - _BaseSpacesServiceRestTransport._BaseEndActiveConference, SpacesServiceRestStub + class _CreateMember( + _BaseSpacesServiceRestTransport._BaseCreateMember, SpacesServiceRestStub ): def __hash__(self): - return hash("SpacesServiceRestTransport.EndActiveConference") + return hash("SpacesServiceRestTransport.CreateMember") @staticmethod def _get_response( @@ -528,18 +812,18 @@ def _get_response( def __call__( self, - request: service.EndActiveConferenceRequest, + request: service.CreateMemberRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): - r"""Call the end active conference method over HTTP. + ) -> resource.Member: + r"""Call the create member method over HTTP. Args: - request (~.service.EndActiveConferenceRequest): - The request object. Request to end an ongoing conference - of a space. + request (~.service.CreateMemberRequest): + The request object. Request to create a member for a + space. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -547,18 +831,25 @@ def __call__( sent along with the request as metadata. Normally, each value must be of type `str`, but for metadata keys ending with the suffix `-bin`, the corresponding values must be of type `bytes`. + + Returns: + ~.resource.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + """ - http_options = _BaseSpacesServiceRestTransport._BaseEndActiveConference._get_http_options() - request, metadata = self._interceptor.pre_end_active_conference( - request, metadata + http_options = ( + _BaseSpacesServiceRestTransport._BaseCreateMember._get_http_options() ) + request, metadata = self._interceptor.pre_create_member(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseSpacesServiceRestTransport._BaseEndActiveConference, - "_BaseEndActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseSpacesServiceRestTransport._BaseCreateMember, + "_BaseCreateMember__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -582,17 +873,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.apps.meet_v2.SpacesServiceClient.EndActiveConference", + f"Sending request for google.apps.meet_v2.SpacesServiceClient.CreateMember", extra={ "serviceName": "google.apps.meet.v2.SpacesService", - "rpcName": "EndActiveConference", + "rpcName": "CreateMember", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = SpacesServiceRestTransport._EndActiveConference._get_response( + response = SpacesServiceRestTransport._CreateMember._get_response( self._host, metadata, query_params, @@ -607,11 +898,45 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetSpace( - _BaseSpacesServiceRestTransport._BaseGetSpace, SpacesServiceRestStub + # Return the response + resp = resource.Member() + pb_resp = resource.Member.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_member(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_member_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.Member.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2.SpacesServiceClient.create_member", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "CreateMember", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSpace( + _BaseSpacesServiceRestTransport._BaseCreateSpace, SpacesServiceRestStub ): def __hash__(self): - return hash("SpacesServiceRestTransport.GetSpace") + return hash("SpacesServiceRestTransport.CreateSpace") @staticmethod def _get_response( @@ -632,12 +957,528 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: service.GetSpaceRequest, + request: service.CreateSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Space: + r"""Call the create space method over HTTP. + + Args: + request (~.service.CreateSpaceRequest): + The request object. Request to create a space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resource.Space: + Virtual place where conferences are + held. Only one active conference can be + held in one space at any given time. + + """ + + http_options = ( + _BaseSpacesServiceRestTransport._BaseCreateSpace._get_http_options() + ) + request, metadata = self._interceptor.pre_create_space(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseCreateSpace, + "_BaseCreateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.SpacesServiceClient.CreateSpace", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "CreateSpace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._CreateSpace._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.Space() + pb_resp = resource.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_space(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_space_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.Space.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2.SpacesServiceClient.create_space", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "CreateSpace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteMember( + _BaseSpacesServiceRestTransport._BaseDeleteMember, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.DeleteMember") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete member method over HTTP. + + Args: + request (~.service.DeleteMemberRequest): + The request object. Request to delete a member from a + space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSpacesServiceRestTransport._BaseDeleteMember._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_member(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseDeleteMember, + "_BaseDeleteMember__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.SpacesServiceClient.DeleteMember", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "DeleteMember", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._DeleteMember._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _EndActiveConference( + _BaseSpacesServiceRestTransport._BaseEndActiveConference, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.EndActiveConference") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.EndActiveConferenceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the end active conference method over HTTP. + + Args: + request (~.service.EndActiveConferenceRequest): + The request object. Request to end an ongoing conference + of a space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseSpacesServiceRestTransport._BaseEndActiveConference._get_http_options() + request, metadata = self._interceptor.pre_end_active_conference( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseEndActiveConference, + "_BaseEndActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.SpacesServiceClient.EndActiveConference", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "EndActiveConference", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._EndActiveConference._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetMember( + _BaseSpacesServiceRestTransport._BaseGetMember, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.GetMember") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Call the get member method over HTTP. + + Args: + request (~.service.GetMemberRequest): + The request object. Request to get a member from a space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resource.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + + http_options = ( + _BaseSpacesServiceRestTransport._BaseGetMember._get_http_options() + ) + request, metadata = self._interceptor.pre_get_member(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseGetMember, + "_BaseGetMember__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.SpacesServiceClient.GetMember", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "GetMember", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._GetMember._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.Member() + pb_resp = resource.Member.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_member(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_member_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.Member.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2.SpacesServiceClient.get_member", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "GetMember", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSpace( + _BaseSpacesServiceRestTransport._BaseGetSpace, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.GetSpace") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetSpaceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, @@ -646,8 +1487,157 @@ def __call__( r"""Call the get space method over HTTP. Args: - request (~.service.GetSpaceRequest): - The request object. Request to get a space. + request (~.service.GetSpaceRequest): + The request object. Request to get a space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resource.Space: + Virtual place where conferences are + held. Only one active conference can be + held in one space at any given time. + + """ + + http_options = ( + _BaseSpacesServiceRestTransport._BaseGetSpace._get_http_options() + ) + request, metadata = self._interceptor.pre_get_space(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseGetSpace, + "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.SpacesServiceClient.GetSpace", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "GetSpace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._GetSpace._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.Space() + pb_resp = resource.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_space(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_space_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.Space.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2.SpacesServiceClient.get_space", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "GetSpace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMembers( + _BaseSpacesServiceRestTransport._BaseListMembers, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.ListMembers") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListMembersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListMembersResponse: + r"""Call the list members method over HTTP. + + Args: + request (~.service.ListMembersRequest): + The request object. Request to list all members of a + space. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -657,23 +1647,169 @@ def __call__( be of type `bytes`. Returns: - ~.resource.Space: - Virtual place where conferences are - held. Only one active conference can be - held in one space at any given time. + ~.service.ListMembersResponse: + Response of list members. + """ + + http_options = ( + _BaseSpacesServiceRestTransport._BaseListMembers._get_http_options() + ) + request, metadata = self._interceptor.pre_list_members(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseListMembers, + "_BaseListMembers__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2.SpacesServiceClient.ListMembers", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "ListMembers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._ListMembers._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListMembersResponse() + pb_resp = service.ListMembersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_members(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_members_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListMembersResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2.SpacesServiceClient.list_members", + extra={ + "serviceName": "google.apps.meet.v2.SpacesService", + "rpcName": "ListMembers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateMember( + _BaseSpacesServiceRestTransport._BaseUpdateMember, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.UpdateMember") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.UpdateMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Call the update member method over HTTP. + + Args: + request (~.service.UpdateMemberRequest): + The request object. Request to update a member. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resource.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. """ http_options = ( - _BaseSpacesServiceRestTransport._BaseGetSpace._get_http_options() + _BaseSpacesServiceRestTransport._BaseUpdateMember._get_http_options() ) - request, metadata = self._interceptor.pre_get_space(request, metadata) + request, metadata = self._interceptor.pre_update_member(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseSpacesServiceRestTransport._BaseGetSpace, - "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseSpacesServiceRestTransport._BaseUpdateMember, + "_BaseUpdateMember__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -697,23 +1833,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.apps.meet_v2.SpacesServiceClient.GetSpace", + f"Sending request for google.apps.meet_v2.SpacesServiceClient.UpdateMember", extra={ "serviceName": "google.apps.meet.v2.SpacesService", - "rpcName": "GetSpace", + "rpcName": "UpdateMember", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = SpacesServiceRestTransport._GetSpace._get_response( + response = SpacesServiceRestTransport._UpdateMember._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -722,21 +1859,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resource.Space() - pb_resp = resource.Space.pb(resp) + resp = resource.Member() + pb_resp = resource.Member.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_space(resp) + resp = self._interceptor.post_update_member(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_space_with_metadata( + resp, _ = self._interceptor.post_update_member_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resource.Space.to_json(response) + response_payload = resource.Member.to_json(response) except: response_payload = None http_response = { @@ -745,10 +1882,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.apps.meet_v2.SpacesServiceClient.get_space", + "Received response for google.apps.meet_v2.SpacesServiceClient.update_member", extra={ "serviceName": "google.apps.meet.v2.SpacesService", - "rpcName": "GetSpace", + "rpcName": "UpdateMember", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -905,12 +2042,34 @@ def __call__( ) return resp + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], service.BatchUpdateMembersResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdateMembers(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_member(self) -> Callable[[service.CreateMemberRequest], resource.Member]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMember(self._session, self._host, self._interceptor) # type: ignore + @property def create_space(self) -> Callable[[service.CreateSpaceRequest], resource.Space]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast return self._CreateSpace(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_member(self) -> Callable[[service.DeleteMemberRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMember(self._session, self._host, self._interceptor) # type: ignore + @property def end_active_conference( self, @@ -919,12 +2078,32 @@ def end_active_conference( # In C++ this would require a dynamic_cast return self._EndActiveConference(self._session, self._host, self._interceptor) # type: ignore + @property + def get_member(self) -> Callable[[service.GetMemberRequest], resource.Member]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMember(self._session, self._host, self._interceptor) # type: ignore + @property def get_space(self) -> Callable[[service.GetSpaceRequest], resource.Space]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast return self._GetSpace(self._session, self._host, self._interceptor) # type: ignore + @property + def list_members( + self, + ) -> Callable[[service.ListMembersRequest], service.ListMembersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMembers(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_member(self) -> Callable[[service.UpdateMemberRequest], resource.Member]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMember(self._session, self._host, self._interceptor) # type: ignore + @property def update_space(self) -> Callable[[service.UpdateSpaceRequest], resource.Space]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest_base.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest_base.py index 7f50a7311dbc..5ee5a11304d6 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest_base.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/transports/rest_base.py @@ -88,6 +88,40 @@ def __init__( api_audience=api_audience, ) + class _BaseBatchUpdateMembers: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=spaces/*}/members:batchUpdate", + "body": "*", + }, + ] + return http_options + + class _BaseCreateMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=spaces/*}/members", + "body": "member", + }, + ] + return http_options + class _BaseCreateSpace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -103,6 +137,22 @@ def _get_http_options(): ] return http_options + class _BaseDeleteMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=spaces/*/members/*}", + }, + ] + return http_options + class _BaseEndActiveConference: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -120,6 +170,22 @@ def _get_http_options(): ] return http_options + class _BaseGetMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=spaces/*/members/*}", + }, + ] + return http_options + class _BaseGetSpace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -136,6 +202,39 @@ def _get_http_options(): ] return http_options + class _BaseListMembers: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=spaces/*}/members", + }, + ] + return http_options + + class _BaseUpdateMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{member.name=spaces/*/members/*}", + "body": "member", + }, + ] + return http_options + class _BaseUpdateSpace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-apps-meet/google/apps/meet_v2/types/__init__.py b/packages/google-apps-meet/google/apps/meet_v2/types/__init__.py index d1cd219bdc84..7ac2cca27cd8 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/types/__init__.py +++ b/packages/google-apps-meet/google/apps/meet_v2/types/__init__.py @@ -19,38 +19,51 @@ ConferenceRecord, DocsDestination, DriveDestination, + Member, Participant, ParticipantSession, PhoneUser, Recording, SignedinUser, + SmartNote, Space, SpaceConfig, Transcript, TranscriptEntry, ) from .service import ( + BatchUpdateMembersRequest, + BatchUpdateMembersResponse, + CreateMemberRequest, CreateSpaceRequest, + DeleteMemberRequest, EndActiveConferenceRequest, GetConferenceRecordRequest, + GetMemberRequest, GetParticipantRequest, GetParticipantSessionRequest, GetRecordingRequest, + GetSmartNoteRequest, GetSpaceRequest, GetTranscriptEntryRequest, GetTranscriptRequest, ListConferenceRecordsRequest, ListConferenceRecordsResponse, + ListMembersRequest, + ListMembersResponse, ListParticipantSessionsRequest, ListParticipantSessionsResponse, ListParticipantsRequest, ListParticipantsResponse, ListRecordingsRequest, ListRecordingsResponse, + ListSmartNotesRequest, + ListSmartNotesResponse, ListTranscriptEntriesRequest, ListTranscriptEntriesResponse, ListTranscriptsRequest, ListTranscriptsResponse, + UpdateMemberRequest, UpdateSpaceRequest, ) @@ -60,35 +73,48 @@ "ConferenceRecord", "DocsDestination", "DriveDestination", + "Member", "Participant", "ParticipantSession", "PhoneUser", "Recording", "SignedinUser", + "SmartNote", "Space", "SpaceConfig", "Transcript", "TranscriptEntry", + "BatchUpdateMembersRequest", + "BatchUpdateMembersResponse", + "CreateMemberRequest", "CreateSpaceRequest", + "DeleteMemberRequest", "EndActiveConferenceRequest", "GetConferenceRecordRequest", + "GetMemberRequest", "GetParticipantRequest", "GetParticipantSessionRequest", "GetRecordingRequest", + "GetSmartNoteRequest", "GetSpaceRequest", "GetTranscriptEntryRequest", "GetTranscriptRequest", "ListConferenceRecordsRequest", "ListConferenceRecordsResponse", + "ListMembersRequest", + "ListMembersResponse", "ListParticipantSessionsRequest", "ListParticipantSessionsResponse", "ListParticipantsRequest", "ListParticipantsResponse", "ListRecordingsRequest", "ListRecordingsResponse", + "ListSmartNotesRequest", + "ListSmartNotesResponse", "ListTranscriptEntriesRequest", "ListTranscriptEntriesResponse", "ListTranscriptsRequest", "ListTranscriptsResponse", + "UpdateMemberRequest", "UpdateSpaceRequest", ) diff --git a/packages/google-apps-meet/google/apps/meet_v2/types/resource.py b/packages/google-apps-meet/google/apps/meet_v2/types/resource.py index a5429c500b46..b16e7833180f 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/types/resource.py +++ b/packages/google-apps-meet/google/apps/meet_v2/types/resource.py @@ -26,6 +26,7 @@ "Space", "ActiveConference", "SpaceConfig", + "Member", "ConferenceRecord", "Participant", "ParticipantSession", @@ -37,6 +38,7 @@ "Transcript", "DocsDestination", "TranscriptEntry", + "SmartNote", }, ) @@ -56,7 +58,7 @@ class Space(proto.Message): example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. meeting_uri (str): Output only. URI used to join meetings consisting of ``https://meet.google.com/`` followed by the @@ -78,8 +80,90 @@ class Space(proto.Message): space. active_conference (google.apps.meet_v2.types.ActiveConference): Active conference, if it exists. + phone_access (MutableSequence[google.apps.meet_v2.types.Space.PhoneAccess]): + Output only. All regional phone access + methods for this meeting space. Can be empty. + gateway_sip_access (MutableSequence[google.apps.meet_v2.types.Space.GatewaySipAccess]): + Output only. The SIP-based access methods + that can be used to join the conference. Can be + empty. """ + class PhoneAccess(proto.Message): + r"""Phone access contains information required to dial into a + conference using a regional phone number and a PIN that is + specific to that phone number. + + Attributes: + phone_number (str): + The phone number to dial for this meeting + space in E.164 format. Full phone number with a + leading '+' character. + pin (str): + The PIN that users must enter after dialing + the given number. The PIN consists of only + decimal digits and the length may vary. + region_code (str): + The CLDR/ISO 3166 region code for the country + associated with this phone access. To be parsed + by the i18n RegionCode utility. Example: "SE" + for Sweden. + language_code (str): + The BCP 47/LDML language code for the + language associated with this phone access. To + be parsed by the i18n LanguageCode utility. + Examples: "es-419" for Latin American Spanish, + "fr-CA" for Canadian French. + """ + + phone_number: str = proto.Field( + proto.STRING, + number=1, + ) + pin: str = proto.Field( + proto.STRING, + number=2, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + + class GatewaySipAccess(proto.Message): + r"""Details how to join the conference through a SIP gateway. + + Attributes: + uri (str): + The Session Initiation Protocol (SIP) URI the conference can + be reached through. + + The string is in one of these formats: + + - "sip:USER_ID@GATEWAY_ADDRESS" + - "sips:USER_ID@GATEWAY_ADDRESS" + + where USER_ID is the 13-digit universal pin (with the future + option to support using a Meet meeting code as well), and + GATEWAY_ADDRESS is a valid address to be resolved using a + DNS SRV lookup, or a dotted quad. + sip_access_code (str): + The permanent numeric code for manual entry + on specially configured devices. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + sip_access_code: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -102,6 +186,16 @@ class Space(proto.Message): number=6, message="ActiveConference", ) + phone_access: MutableSequence[PhoneAccess] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=PhoneAccess, + ) + gateway_sip_access: MutableSequence[GatewaySipAccess] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=GatewaySipAccess, + ) class ActiveConference(proto.Message): @@ -135,6 +229,22 @@ class SpaceConfig(proto.Message): Defines the entry points that can be used to join meetings hosted in this meeting space. Default: EntryPointAccess.ALL + moderation (google.apps.meet_v2.types.SpaceConfig.Moderation): + The pre-configured moderation mode for the + Meeting. Default: Controlled by the user's + policies. + moderation_restrictions (google.apps.meet_v2.types.SpaceConfig.ModerationRestrictions): + When moderation.ON, these restrictions go + into effect for the meeting. When + moderation.OFF, will be reset to default + ModerationRestrictions. + attendance_report_generation_type (google.apps.meet_v2.types.SpaceConfig.AttendanceReportGenerationType): + Whether attendance report is enabled for the + meeting space. + artifact_config (google.apps.meet_v2.types.SpaceConfig.ArtifactConfig): + Configuration pertaining to the + auto-generated artifacts that the meeting + supports. """ class AccessType(proto.Enum): @@ -185,6 +295,233 @@ class EntryPointAccess(proto.Enum): ALL = 1 CREATOR_APP_ONLY = 2 + class Moderation(proto.Enum): + r"""The moderation mode for a meeting. When the moderation mode + is on, the meeting owner has more control over the meeting with + features such as co-host management (see message Member) and + feature restrictions (see message ModerationRestrictions). + + Values: + MODERATION_UNSPECIFIED (0): + Moderation type is not specified. This is + used to indicate the user hasn't specified any + value as the user does not intend to update the + state. Users are not allowed to set the value as + unspecified. + OFF (1): + Moderation is off. + ON (2): + Moderation is on. + """ + + MODERATION_UNSPECIFIED = 0 + OFF = 1 + ON = 2 + + class AttendanceReportGenerationType(proto.Enum): + r"""Possible states of whether attendance report is enabled for + the meeting space. + + Values: + ATTENDANCE_REPORT_GENERATION_TYPE_UNSPECIFIED (0): + Default value specified by user policy. + This should never be returned. + GENERATE_REPORT (1): + Attendance report will be generated and sent + to drive/email. + DO_NOT_GENERATE (2): + Attendance report will not be generated. + """ + + ATTENDANCE_REPORT_GENERATION_TYPE_UNSPECIFIED = 0 + GENERATE_REPORT = 1 + DO_NOT_GENERATE = 2 + + class ModerationRestrictions(proto.Message): + r"""Defines restrictions for features when the meeting is + moderated. + + Attributes: + chat_restriction (google.apps.meet_v2.types.SpaceConfig.ModerationRestrictions.RestrictionType): + Defines who has permission to send chat + messages in the meeting space. + reaction_restriction (google.apps.meet_v2.types.SpaceConfig.ModerationRestrictions.RestrictionType): + Defines who has permission to send reactions + in the meeting space. + present_restriction (google.apps.meet_v2.types.SpaceConfig.ModerationRestrictions.RestrictionType): + Defines who has permission to share their + screen in the meeting space. + default_join_as_viewer_type (google.apps.meet_v2.types.SpaceConfig.ModerationRestrictions.DefaultJoinAsViewerType): + Defines whether to restrict the default role + assigned to users as viewer. + """ + + class RestrictionType(proto.Enum): + r"""Determines who has permission to use a particular feature. + + Values: + RESTRICTION_TYPE_UNSPECIFIED (0): + Default value specified by user policy. + This should never be returned. + HOSTS_ONLY (1): + Meeting owner and co-host have the + permission. + NO_RESTRICTION (2): + All Participants have permissions. + """ + + RESTRICTION_TYPE_UNSPECIFIED = 0 + HOSTS_ONLY = 1 + NO_RESTRICTION = 2 + + class DefaultJoinAsViewerType(proto.Enum): + r"""By default users will join as contributors. Hosts can + restrict users to join as viewers. + Note: If an explicit role is set for a user in the Member + resource, the user will join as that role. + + Values: + DEFAULT_JOIN_AS_VIEWER_TYPE_UNSPECIFIED (0): + Default value specified by user policy. + This should never be returned. + ON (1): + Users will by default join as viewers. + OFF (2): + Users will by default join as contributors. + """ + + DEFAULT_JOIN_AS_VIEWER_TYPE_UNSPECIFIED = 0 + ON = 1 + OFF = 2 + + chat_restriction: "SpaceConfig.ModerationRestrictions.RestrictionType" = ( + proto.Field( + proto.ENUM, + number=1, + enum="SpaceConfig.ModerationRestrictions.RestrictionType", + ) + ) + reaction_restriction: "SpaceConfig.ModerationRestrictions.RestrictionType" = ( + proto.Field( + proto.ENUM, + number=2, + enum="SpaceConfig.ModerationRestrictions.RestrictionType", + ) + ) + present_restriction: "SpaceConfig.ModerationRestrictions.RestrictionType" = ( + proto.Field( + proto.ENUM, + number=3, + enum="SpaceConfig.ModerationRestrictions.RestrictionType", + ) + ) + default_join_as_viewer_type: "SpaceConfig.ModerationRestrictions.DefaultJoinAsViewerType" = proto.Field( + proto.ENUM, + number=4, + enum="SpaceConfig.ModerationRestrictions.DefaultJoinAsViewerType", + ) + + class ArtifactConfig(proto.Message): + r"""Configuration related to meeting artifacts potentially + generated by this meeting space. + + Attributes: + recording_config (google.apps.meet_v2.types.SpaceConfig.ArtifactConfig.RecordingConfig): + Configuration for recording. + transcription_config (google.apps.meet_v2.types.SpaceConfig.ArtifactConfig.TranscriptionConfig): + Configuration for auto-transcript. + smart_notes_config (google.apps.meet_v2.types.SpaceConfig.ArtifactConfig.SmartNotesConfig): + Configuration for auto-smart-notes. + """ + + class AutoGenerationType(proto.Enum): + r"""Determines whether an artifact can be automatically generated + in the meeting space. + + Values: + AUTO_GENERATION_TYPE_UNSPECIFIED (0): + Default value specified by user policy. + This should never be returned. + ON (1): + The artifact is generated automatically. + OFF (2): + The artifact is not generated automatically. + """ + + AUTO_GENERATION_TYPE_UNSPECIFIED = 0 + ON = 1 + OFF = 2 + + class RecordingConfig(proto.Message): + r"""Configuration related to recording in a meeting space. + + Attributes: + auto_recording_generation (google.apps.meet_v2.types.SpaceConfig.ArtifactConfig.AutoGenerationType): + Defines whether a meeting space is + automatically recorded when someone with the + privilege to record joins the meeting. + """ + + auto_recording_generation: "SpaceConfig.ArtifactConfig.AutoGenerationType" = proto.Field( + proto.ENUM, + number=2, + enum="SpaceConfig.ArtifactConfig.AutoGenerationType", + ) + + class TranscriptionConfig(proto.Message): + r"""Configuration related to transcription in a meeting space. + + Attributes: + auto_transcription_generation (google.apps.meet_v2.types.SpaceConfig.ArtifactConfig.AutoGenerationType): + Defines whether the content of a meeting is + automatically transcribed when someone with the + privilege to transcribe joins the meeting. + """ + + auto_transcription_generation: "SpaceConfig.ArtifactConfig.AutoGenerationType" = proto.Field( + proto.ENUM, + number=2, + enum="SpaceConfig.ArtifactConfig.AutoGenerationType", + ) + + class SmartNotesConfig(proto.Message): + r"""Configuration related to smart notes in a meeting space. For more + information about smart notes, see `"Take notes for me" in Google + Meet `__. + + Attributes: + auto_smart_notes_generation (google.apps.meet_v2.types.SpaceConfig.ArtifactConfig.AutoGenerationType): + Defines whether to automatically generate a + summary and recap of the meeting for all + invitees in the organization when someone with + the privilege to enable smart notes joins the + meeting. + """ + + auto_smart_notes_generation: "SpaceConfig.ArtifactConfig.AutoGenerationType" = proto.Field( + proto.ENUM, + number=2, + enum="SpaceConfig.ArtifactConfig.AutoGenerationType", + ) + + recording_config: "SpaceConfig.ArtifactConfig.RecordingConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="SpaceConfig.ArtifactConfig.RecordingConfig", + ) + transcription_config: "SpaceConfig.ArtifactConfig.TranscriptionConfig" = ( + proto.Field( + proto.MESSAGE, + number=2, + message="SpaceConfig.ArtifactConfig.TranscriptionConfig", + ) + ) + smart_notes_config: "SpaceConfig.ArtifactConfig.SmartNotesConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="SpaceConfig.ArtifactConfig.SmartNotesConfig", + ) + access_type: AccessType = proto.Field( proto.ENUM, number=1, @@ -195,6 +532,74 @@ class EntryPointAccess(proto.Enum): number=2, enum=EntryPointAccess, ) + moderation: Moderation = proto.Field( + proto.ENUM, + number=3, + enum=Moderation, + ) + moderation_restrictions: ModerationRestrictions = proto.Field( + proto.MESSAGE, + number=4, + message=ModerationRestrictions, + ) + attendance_report_generation_type: AttendanceReportGenerationType = proto.Field( + proto.ENUM, + number=6, + enum=AttendanceReportGenerationType, + ) + artifact_config: ArtifactConfig = proto.Field( + proto.MESSAGE, + number=7, + message=ArtifactConfig, + ) + + +class Member(proto.Message): + r"""Users who are configured to have a role in the space. These + users can join the space without knocking. + + Attributes: + name (str): + Identifier. Resource name of the member. + Format: spaces/{space}/members/{member} + email (str): + Email for the member. This is required for + creating the member. + role (google.apps.meet_v2.types.Member.Role): + The meeting role assigned to the member. + """ + + class Role(proto.Enum): + r"""Role of this member in the space. + + Values: + ROLE_UNSPECIFIED (0): + This is used to indicate the user hasn't specified any value + and the user’s role will be determined upon joining the + meetings between 'contributor' and 'viewer' role depending + on meeting configuration. For more information about the + viewer role, see `Assign View only roles in Google + Meet `__. + COHOST (1): + Co-host role. + """ + + ROLE_UNSPECIFIED = 0 + COHOST = 1 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + email: str = proto.Field( + proto.STRING, + number=2, + ) + role: Role = proto.Field( + proto.ENUM, + number=3, + enum=Role, + ) class ConferenceRecord(proto.Message): @@ -674,4 +1079,82 @@ class TranscriptEntry(proto.Message): ) +class SmartNote(proto.Message): + r"""Metadata for a smart note generated from a conference. It + refers to the notes generated from Take Notes with Gemini during + the conference. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + docs_destination (google.apps.meet_v2.types.DocsDestination): + Output only. The Google Doc destination where + the smart notes are saved. + + This field is a member of `oneof`_ ``destination``. + name (str): + Output only. Identifier. Resource name of the smart notes. + Format: + ``conferenceRecords/{conference_record}/smartNotes/{smart_note}``, + where ``{smart_note}`` is a 1:1 mapping to each unique smart + notes session of the conference. + state (google.apps.meet_v2.types.SmartNote.State): + Output only. Current state. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the smart notes + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the smart notes + stopped. + """ + + class State(proto.Enum): + r"""Current state of the smart notes session. + + Values: + STATE_UNSPECIFIED (0): + Default, never used. + STARTED (1): + An active smart notes session has started. + ENDED (2): + This smart notes session has ended, but the + smart notes file hasn't been generated yet. + FILE_GENERATED (3): + Smart notes file is generated and ready to + download. + """ + + STATE_UNSPECIFIED = 0 + STARTED = 1 + ENDED = 2 + FILE_GENERATED = 3 + + docs_destination: "DocsDestination" = proto.Field( + proto.MESSAGE, + number=5, + oneof="destination", + message="DocsDestination", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-meet/google/apps/meet_v2/types/service.py b/packages/google-apps-meet/google/apps/meet_v2/types/service.py index 8e0a655173c9..1d9836d782dc 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/types/service.py +++ b/packages/google-apps-meet/google/apps/meet_v2/types/service.py @@ -29,6 +29,14 @@ "GetSpaceRequest", "UpdateSpaceRequest", "EndActiveConferenceRequest", + "CreateMemberRequest", + "GetMemberRequest", + "ListMembersRequest", + "ListMembersResponse", + "DeleteMemberRequest", + "UpdateMemberRequest", + "BatchUpdateMembersRequest", + "BatchUpdateMembersResponse", "GetConferenceRecordRequest", "ListConferenceRecordsRequest", "ListConferenceRecordsResponse", @@ -47,6 +55,9 @@ "GetTranscriptEntryRequest", "ListTranscriptEntriesRequest", "ListTranscriptEntriesResponse", + "GetSmartNoteRequest", + "ListSmartNotesRequest", + "ListSmartNotesResponse", }, ) @@ -95,7 +106,7 @@ class GetSpaceRequest(proto.Message): Meet `__. For more information, see `How Meet identifies a meeting - space `__. + space `__. """ name: str = proto.Field( @@ -145,7 +156,7 @@ class EndActiveConferenceRequest(proto.Message): example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. """ name: str = proto.Field( @@ -154,6 +165,217 @@ class EndActiveConferenceRequest(proto.Message): ) +class CreateMemberRequest(proto.Message): + r"""Request to create a member for a space. + + Attributes: + parent (str): + Required. Format: spaces/{space} + member (google.apps.meet_v2.types.Member): + Required. The member to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + member: resource.Member = proto.Field( + proto.MESSAGE, + number=2, + message=resource.Member, + ) + + +class GetMemberRequest(proto.Message): + r"""Request to get a member from a space. + + Attributes: + name (str): + Required. Format: + “spaces/{space}/members/{member}” + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMembersRequest(proto.Message): + r"""Request to list all members of a space. + + Attributes: + parent (str): + Required. Format: spaces/{space} + page_size (int): + Optional. Maximum number of members to + return. The service might return fewer than this + value. If unspecified or set to 0, at most 250 + members are returned. The maximum value is 500; + values above 500 are coerced to 500. Maximum + might change in the future. + page_token (str): + Optional. Page token returned from previous + List Call. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMembersResponse(proto.Message): + r"""Response of list members. + + Attributes: + members (MutableSequence[google.apps.meet_v2.types.Member]): + The list of members for the current page. + next_page_token (str): + Token to be circulated back for further list + call if current list doesn't include all the + members. Unset if all members are returned. + """ + + @property + def raw_page(self): + return self + + members: MutableSequence[resource.Member] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resource.Member, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteMemberRequest(proto.Message): + r"""Request to delete a member from a space. + + Attributes: + name (str): + Required. Format: + “spaces/{space}/members/{member}” + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateMemberRequest(proto.Message): + r"""Request to update a member. + + Attributes: + member (google.apps.meet_v2.types.Member): + Required. The Member to update. + Format: spaces/{space}/members/{member} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask used to specify the fields to be + updated in the member. If update_mask isn't provided(not + set, set with empty paths, or only has "" as paths), it + defaults to update all fields provided with values in the + request. Using "\*" as update_mask will update all fields, + including deleting fields not set in the request. In case of + BatchUpdate, it must be absent or the same as the + update_mask in BatchUpdateMembersRequest when + UpdateMemberRequest is built as a child request of + BatchUpdateMembersRequest. + """ + + member: resource.Member = proto.Field( + proto.MESSAGE, + number=1, + message=resource.Member, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateMembersRequest(proto.Message): + r"""Request to update members of one space within a batch. + + Attributes: + parent (str): + Required. The parent resource shared by all + Members being updated. Format: spaces/{space} + requests (MutableSequence[google.apps.meet_v2.types.UpdateMemberRequest]): + Required. The request message specifying the + resources to update. A maximum of 500 members + can be modified in a batch. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Top-level field mask used to + specify the fields to be updated in the member + for all UpdateMemberRequests. There are 4 + possible scenarios for top-level and child field + mask: + + 1. top-level and child field mask is absent: + + All fields provided in the requests are + updated, including deleting fields not set in + the requests. + 2. top-level field mask is present but child + field mask is absent: + + The fields specified in the top-level field + mask are updated. + 3. top-level and child field mask is present: + + The child field mask must be the same as the + top-level field mask. + 4. top-level field mask is absent but child + field mask is present: + + It isn't supported and will return an error. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["UpdateMemberRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="UpdateMemberRequest", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateMembersResponse(proto.Message): + r"""Response of batch update members. + + Attributes: + members (MutableSequence[google.apps.meet_v2.types.Member]): + Members updated. + """ + + members: MutableSequence[resource.Member] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resource.Member, + ) + + class GetConferenceRecordRequest(proto.Message): r"""Request to get a conference record. @@ -652,4 +874,79 @@ def raw_page(self): ) +class GetSmartNoteRequest(proto.Message): + r"""Request for GetSmartNote method. + + Attributes: + name (str): + Required. Resource name of the smart note. Format: + conferenceRecords/{conference_record}/smartNotes/{smart_note} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSmartNotesRequest(proto.Message): + r"""Request for ListSmartNotes method. + + Attributes: + parent (str): + Required. Format: ``conferenceRecords/{conference_record}`` + page_size (int): + Optional. Maximum number of smart notes to + return. The service might return fewer than this + value. If unspecified, at most 10 smart notes + are returned. The maximum value is 100; values + above 100 are coerced to 100. Maximum might + change in the future. + page_token (str): + Optional. Page token returned from previous + List Call. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSmartNotesResponse(proto.Message): + r"""Response for ListSmartNotes method. + + Attributes: + smart_notes (MutableSequence[google.apps.meet_v2.types.SmartNote]): + List of smart notes in one page. + next_page_token (str): + Token to be circulated back for further List + call if current List doesn't include all the + smart notes. Unset if all smart notes are + returned. + """ + + @property + def raw_page(self): + return self + + smart_notes: MutableSequence[resource.SmartNote] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resource.SmartNote, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/__init__.py b/packages/google-apps-meet/google/apps/meet_v2beta/__init__.py index 7a9d8180234f..aa02ea2ed662 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/__init__.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/__init__.py @@ -50,12 +50,15 @@ PhoneUser, Recording, SignedinUser, + SmartNote, Space, SpaceConfig, Transcript, TranscriptEntry, ) from .types.service import ( + BatchUpdateMembersRequest, + BatchUpdateMembersResponse, ConnectActiveConferenceRequest, ConnectActiveConferenceResponse, CreateMemberRequest, @@ -67,6 +70,7 @@ GetParticipantRequest, GetParticipantSessionRequest, GetRecordingRequest, + GetSmartNoteRequest, GetSpaceRequest, GetTranscriptEntryRequest, GetTranscriptRequest, @@ -80,10 +84,13 @@ ListParticipantsResponse, ListRecordingsRequest, ListRecordingsResponse, + ListSmartNotesRequest, + ListSmartNotesResponse, ListTranscriptEntriesRequest, ListTranscriptEntriesResponse, ListTranscriptsRequest, ListTranscriptsResponse, + UpdateMemberRequest, UpdateSpaceRequest, ) @@ -92,6 +99,8 @@ "SpacesServiceAsyncClient", "ActiveConference", "AnonymousUser", + "BatchUpdateMembersRequest", + "BatchUpdateMembersResponse", "ConferenceRecord", "ConferenceRecordsServiceClient", "ConnectActiveConferenceRequest", @@ -107,6 +116,7 @@ "GetParticipantRequest", "GetParticipantSessionRequest", "GetRecordingRequest", + "GetSmartNoteRequest", "GetSpaceRequest", "GetTranscriptEntryRequest", "GetTranscriptRequest", @@ -120,6 +130,8 @@ "ListParticipantsResponse", "ListRecordingsRequest", "ListRecordingsResponse", + "ListSmartNotesRequest", + "ListSmartNotesResponse", "ListTranscriptEntriesRequest", "ListTranscriptEntriesResponse", "ListTranscriptsRequest", @@ -130,11 +142,13 @@ "PhoneUser", "Recording", "SignedinUser", + "SmartNote", "Space", "SpaceConfig", "SpacesServiceClient", "Transcript", "TranscriptEntry", + "UpdateMemberRequest", "UpdateSpaceRequest", ) diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/gapic_metadata.json b/packages/google-apps-meet/google/apps/meet_v2beta/gapic_metadata.json index e3b31a932bef..3bf01ab0e198 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/gapic_metadata.json +++ b/packages/google-apps-meet/google/apps/meet_v2beta/gapic_metadata.json @@ -30,6 +30,11 @@ "get_recording" ] }, + "GetSmartNote": { + "methods": [ + "get_smart_note" + ] + }, "GetTranscript": { "methods": [ "get_transcript" @@ -60,6 +65,11 @@ "list_recordings" ] }, + "ListSmartNotes": { + "methods": [ + "list_smart_notes" + ] + }, "ListTranscriptEntries": { "methods": [ "list_transcript_entries" @@ -95,6 +105,11 @@ "get_recording" ] }, + "GetSmartNote": { + "methods": [ + "get_smart_note" + ] + }, "GetTranscript": { "methods": [ "get_transcript" @@ -125,6 +140,11 @@ "list_recordings" ] }, + "ListSmartNotes": { + "methods": [ + "list_smart_notes" + ] + }, "ListTranscriptEntries": { "methods": [ "list_transcript_entries" @@ -160,6 +180,11 @@ "get_recording" ] }, + "GetSmartNote": { + "methods": [ + "get_smart_note" + ] + }, "GetTranscript": { "methods": [ "get_transcript" @@ -190,6 +215,11 @@ "list_recordings" ] }, + "ListSmartNotes": { + "methods": [ + "list_smart_notes" + ] + }, "ListTranscriptEntries": { "methods": [ "list_transcript_entries" @@ -209,6 +239,11 @@ "grpc": { "libraryClient": "SpacesServiceClient", "rpcs": { + "BatchUpdateMembers": { + "methods": [ + "batch_update_members" + ] + }, "ConnectActiveConference": { "methods": [ "connect_active_conference" @@ -249,6 +284,11 @@ "list_members" ] }, + "UpdateMember": { + "methods": [ + "update_member" + ] + }, "UpdateSpace": { "methods": [ "update_space" @@ -259,6 +299,11 @@ "grpc-async": { "libraryClient": "SpacesServiceAsyncClient", "rpcs": { + "BatchUpdateMembers": { + "methods": [ + "batch_update_members" + ] + }, "ConnectActiveConference": { "methods": [ "connect_active_conference" @@ -299,6 +344,11 @@ "list_members" ] }, + "UpdateMember": { + "methods": [ + "update_member" + ] + }, "UpdateSpace": { "methods": [ "update_space" @@ -309,6 +359,11 @@ "rest": { "libraryClient": "SpacesServiceClient", "rpcs": { + "BatchUpdateMembers": { + "methods": [ + "batch_update_members" + ] + }, "ConnectActiveConference": { "methods": [ "connect_active_conference" @@ -349,6 +404,11 @@ "list_members" ] }, + "UpdateMember": { + "methods": [ + "update_member" + ] + }, "UpdateSpace": { "methods": [ "update_space" diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py b/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py index 7d9863d19611..acc458e7fa6f 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.0" # {x-release-please-version} +__version__ = "0.5.1" # {x-release-please-version} diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/async_client.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/async_client.py index 9bd65e8b2872..caff530829bc 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/async_client.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/async_client.py @@ -97,6 +97,10 @@ class ConferenceRecordsServiceAsyncClient: parse_recording_path = staticmethod( ConferenceRecordsServiceClient.parse_recording_path ) + smart_note_path = staticmethod(ConferenceRecordsServiceClient.smart_note_path) + parse_smart_note_path = staticmethod( + ConferenceRecordsServiceClient.parse_smart_note_path + ) space_path = staticmethod(ConferenceRecordsServiceClient.space_path) parse_space_path = staticmethod(ConferenceRecordsServiceClient.parse_space_path) transcript_path = staticmethod(ConferenceRecordsServiceClient.transcript_path) @@ -1523,7 +1527,8 @@ async def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. .. code-block:: python @@ -1639,7 +1644,8 @@ async def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -1758,6 +1764,245 @@ async def sample_list_transcript_entries(): # Done; return the response. return response + async def get_smart_note( + self, + request: Optional[Union[service.GetSmartNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.SmartNote: + r"""Gets smart notes by smart note ID. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + async def sample_get_smart_note(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_smart_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2beta.types.GetSmartNoteRequest, dict]]): + The request object. Request for GetSmartNote method. + name (:class:`str`): + Required. Resource name of the smart note. Format: + conferenceRecords/{conference_record}/smartNotes/{smart_note} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.types.SmartNote: + Metadata for a smart note generated + from a conference. It refers to the + notes generated from Take Notes with + Gemini during the conference. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetSmartNoteRequest): + request = service.GetSmartNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_smart_note + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_smart_notes( + self, + request: Optional[Union[service.ListSmartNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSmartNotesAsyncPager: + r"""Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + async def sample_list_smart_notes(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2beta.types.ListSmartNotesRequest, dict]]): + The request object. Request for ListSmartNotes method. + parent (:class:`str`): + Required. Format: + ``conferenceRecords/{conference_record}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.services.conference_records_service.pagers.ListSmartNotesAsyncPager: + Response for ListSmartNotes method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListSmartNotesRequest): + request = service.ListSmartNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_smart_notes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSmartNotesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "ConferenceRecordsServiceAsyncClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py index 32ba1d7cdfe2..bedc0c008139 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py @@ -250,6 +250,26 @@ def parse_recording_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def smart_note_path( + conference_record: str, + smart_note: str, + ) -> str: + """Returns a fully-qualified smart_note string.""" + return "conferenceRecords/{conference_record}/smartNotes/{smart_note}".format( + conference_record=conference_record, + smart_note=smart_note, + ) + + @staticmethod + def parse_smart_note_path(path: str) -> Dict[str, str]: + """Parses a smart_note path into its component segments.""" + m = re.match( + r"^conferenceRecords/(?P.+?)/smartNotes/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def space_path( space: str, @@ -1870,7 +1890,8 @@ def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. .. code-block:: python @@ -1983,7 +2004,8 @@ def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -2099,6 +2121,239 @@ def sample_list_transcript_entries(): # Done; return the response. return response + def get_smart_note( + self, + request: Optional[Union[service.GetSmartNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.SmartNote: + r"""Gets smart notes by smart note ID. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + def sample_get_smart_note(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_smart_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2beta.types.GetSmartNoteRequest, dict]): + The request object. Request for GetSmartNote method. + name (str): + Required. Resource name of the smart note. Format: + conferenceRecords/{conference_record}/smartNotes/{smart_note} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.types.SmartNote: + Metadata for a smart note generated + from a conference. It refers to the + notes generated from Take Notes with + Gemini during the conference. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetSmartNoteRequest): + request = service.GetSmartNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_smart_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_smart_notes( + self, + request: Optional[Union[service.ListSmartNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSmartNotesPager: + r"""Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + def sample_list_smart_notes(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.meet_v2beta.types.ListSmartNotesRequest, dict]): + The request object. Request for ListSmartNotes method. + parent (str): + Required. Format: + ``conferenceRecords/{conference_record}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.services.conference_records_service.pagers.ListSmartNotesPager: + Response for ListSmartNotes method. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListSmartNotesRequest): + request = service.ListSmartNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_smart_notes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSmartNotesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ConferenceRecordsServiceClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/pagers.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/pagers.py index 13af0c87613a..dccab54ec989 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/pagers.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/pagers.py @@ -975,3 +975,159 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSmartNotesPager: + """A pager for iterating through ``list_smart_notes`` requests. + + This class thinly wraps an initial + :class:`google.apps.meet_v2beta.types.ListSmartNotesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``smart_notes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSmartNotes`` requests and continue to iterate + through the ``smart_notes`` field on the + corresponding responses. + + All the usual :class:`google.apps.meet_v2beta.types.ListSmartNotesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListSmartNotesResponse], + request: service.ListSmartNotesRequest, + response: service.ListSmartNotesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.meet_v2beta.types.ListSmartNotesRequest): + The initial request object. + response (google.apps.meet_v2beta.types.ListSmartNotesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListSmartNotesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListSmartNotesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resource.SmartNote]: + for page in self.pages: + yield from page.smart_notes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSmartNotesAsyncPager: + """A pager for iterating through ``list_smart_notes`` requests. + + This class thinly wraps an initial + :class:`google.apps.meet_v2beta.types.ListSmartNotesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``smart_notes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSmartNotes`` requests and continue to iterate + through the ``smart_notes`` field on the + corresponding responses. + + All the usual :class:`google.apps.meet_v2beta.types.ListSmartNotesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListSmartNotesResponse]], + request: service.ListSmartNotesRequest, + response: service.ListSmartNotesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.meet_v2beta.types.ListSmartNotesRequest): + The initial request object. + response (google.apps.meet_v2beta.types.ListSmartNotesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListSmartNotesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListSmartNotesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resource.SmartNote]: + async def async_generator(): + async for page in self.pages: + for response in page.smart_notes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/base.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/base.py index f2cbc3f0415a..ae62e20ec48e 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/base.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/base.py @@ -311,6 +311,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_smart_note: gapic_v1.method.wrap_method( + self.get_smart_note, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_smart_notes: gapic_v1.method.wrap_method( + self.list_smart_notes, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), } def close(self): @@ -446,6 +474,26 @@ def list_transcript_entries( ]: raise NotImplementedError() + @property + def get_smart_note( + self, + ) -> Callable[ + [service.GetSmartNoteRequest], + Union[resource.SmartNote, Awaitable[resource.SmartNote]], + ]: + raise NotImplementedError() + + @property + def list_smart_notes( + self, + ) -> Callable[ + [service.ListSmartNotesRequest], + Union[ + service.ListSmartNotesResponse, Awaitable[service.ListSmartNotesResponse] + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc.py index b20cda29393e..239dc2f8ebc8 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc.py @@ -614,7 +614,8 @@ def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. Returns: @@ -649,7 +650,8 @@ def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -671,6 +673,60 @@ def list_transcript_entries( ) return self._stubs["list_transcript_entries"] + @property + def get_smart_note( + self, + ) -> Callable[[service.GetSmartNoteRequest], resource.SmartNote]: + r"""Return a callable for the get smart note method over gRPC. + + Gets smart notes by smart note ID. + + Returns: + Callable[[~.GetSmartNoteRequest], + ~.SmartNote]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_smart_note" not in self._stubs: + self._stubs["get_smart_note"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.ConferenceRecordsService/GetSmartNote", + request_serializer=service.GetSmartNoteRequest.serialize, + response_deserializer=resource.SmartNote.deserialize, + ) + return self._stubs["get_smart_note"] + + @property + def list_smart_notes( + self, + ) -> Callable[[service.ListSmartNotesRequest], service.ListSmartNotesResponse]: + r"""Return a callable for the list smart notes method over gRPC. + + Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + Returns: + Callable[[~.ListSmartNotesRequest], + ~.ListSmartNotesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_smart_notes" not in self._stubs: + self._stubs["list_smart_notes"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.ConferenceRecordsService/ListSmartNotes", + request_serializer=service.ListSmartNotesRequest.serialize, + response_deserializer=service.ListSmartNotesResponse.deserialize, + ) + return self._stubs["list_smart_notes"] + def close(self): self._logged_channel.close() diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc_asyncio.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc_asyncio.py index b8f12156af7e..df78de11e24f 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc_asyncio.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/grpc_asyncio.py @@ -635,7 +635,8 @@ def get_transcript_entry( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the Google Docs - transcript file. This can occur when the Google Docs transcript + transcript file. This can occur when 1) we have interleaved + speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. Returns: @@ -671,7 +672,8 @@ def list_transcript_entries( Note: The transcript entries returned by the Google Meet API might not match the transcription found in the - Google Docs transcript file. This can occur when the + Google Docs transcript file. This can occur when 1) we + have interleaved speakers within milliseconds, or 2) the Google Docs transcript file is modified after generation. @@ -693,6 +695,62 @@ def list_transcript_entries( ) return self._stubs["list_transcript_entries"] + @property + def get_smart_note( + self, + ) -> Callable[[service.GetSmartNoteRequest], Awaitable[resource.SmartNote]]: + r"""Return a callable for the get smart note method over gRPC. + + Gets smart notes by smart note ID. + + Returns: + Callable[[~.GetSmartNoteRequest], + Awaitable[~.SmartNote]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_smart_note" not in self._stubs: + self._stubs["get_smart_note"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.ConferenceRecordsService/GetSmartNote", + request_serializer=service.GetSmartNoteRequest.serialize, + response_deserializer=resource.SmartNote.deserialize, + ) + return self._stubs["get_smart_note"] + + @property + def list_smart_notes( + self, + ) -> Callable[ + [service.ListSmartNotesRequest], Awaitable[service.ListSmartNotesResponse] + ]: + r"""Return a callable for the list smart notes method over gRPC. + + Lists the set of smart notes from the conference + record. By default, ordered by start time and in + ascending order. + + Returns: + Callable[[~.ListSmartNotesRequest], + Awaitable[~.ListSmartNotesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_smart_notes" not in self._stubs: + self._stubs["list_smart_notes"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.ConferenceRecordsService/ListSmartNotes", + request_serializer=service.ListSmartNotesRequest.serialize, + response_deserializer=service.ListSmartNotesResponse.deserialize, + ) + return self._stubs["list_smart_notes"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -864,6 +922,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_smart_note: self._wrap_method( + self.get_smart_note, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_smart_notes: self._wrap_method( + self.list_smart_notes, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest.py index 2f114ef2f887..774d65569053 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest.py @@ -104,6 +104,14 @@ def post_get_recording(self, response): logging.log(f"Received response: {response}") return response + def pre_get_smart_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_smart_note(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_transcript(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -152,6 +160,14 @@ def post_list_recordings(self, response): logging.log(f"Received response: {response}") return response + def pre_list_smart_notes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_smart_notes(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_transcript_entries(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -360,6 +376,50 @@ def post_get_recording_with_metadata( """ return response, metadata + def pre_get_smart_note( + self, + request: service.GetSmartNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetSmartNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_smart_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConferenceRecordsService server. + """ + return request, metadata + + def post_get_smart_note(self, response: resource.SmartNote) -> resource.SmartNote: + """Post-rpc interceptor for get_smart_note + + DEPRECATED. Please use the `post_get_smart_note_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ConferenceRecordsService server but before + it is returned to user code. This `post_get_smart_note` interceptor runs + before the `post_get_smart_note_with_metadata` interceptor. + """ + return response + + def post_get_smart_note_with_metadata( + self, + response: resource.SmartNote, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.SmartNote, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_smart_note + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ConferenceRecordsService server but before it is returned to user code. + + We recommend only using this `post_get_smart_note_with_metadata` + interceptor in new development instead of the `post_get_smart_note` interceptor. + When both interceptors are used, this `post_get_smart_note_with_metadata` interceptor runs after the + `post_get_smart_note` interceptor. The (possibly modified) response returned by + `post_get_smart_note` will be passed to + `post_get_smart_note_with_metadata`. + """ + return response, metadata + def pre_get_transcript( self, request: service.GetTranscriptRequest, @@ -648,6 +708,52 @@ def post_list_recordings_with_metadata( """ return response, metadata + def pre_list_smart_notes( + self, + request: service.ListSmartNotesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListSmartNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_smart_notes + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConferenceRecordsService server. + """ + return request, metadata + + def post_list_smart_notes( + self, response: service.ListSmartNotesResponse + ) -> service.ListSmartNotesResponse: + """Post-rpc interceptor for list_smart_notes + + DEPRECATED. Please use the `post_list_smart_notes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ConferenceRecordsService server but before + it is returned to user code. This `post_list_smart_notes` interceptor runs + before the `post_list_smart_notes_with_metadata` interceptor. + """ + return response + + def post_list_smart_notes_with_metadata( + self, + response: service.ListSmartNotesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListSmartNotesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_smart_notes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ConferenceRecordsService server but before it is returned to user code. + + We recommend only using this `post_list_smart_notes_with_metadata` + interceptor in new development instead of the `post_list_smart_notes` interceptor. + When both interceptors are used, this `post_list_smart_notes_with_metadata` interceptor runs after the + `post_list_smart_notes` interceptor. The (possibly modified) response returned by + `post_list_smart_notes` will be passed to + `post_list_smart_notes_with_metadata`. + """ + return response, metadata + def pre_list_transcript_entries( self, request: service.ListTranscriptEntriesRequest, @@ -1440,6 +1546,156 @@ def __call__( ) return resp + class _GetSmartNote( + _BaseConferenceRecordsServiceRestTransport._BaseGetSmartNote, + ConferenceRecordsServiceRestStub, + ): + def __hash__(self): + return hash("ConferenceRecordsServiceRestTransport.GetSmartNote") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetSmartNoteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.SmartNote: + r"""Call the get smart note method over HTTP. + + Args: + request (~.service.GetSmartNoteRequest): + The request object. Request for GetSmartNote method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resource.SmartNote: + Metadata for a smart note generated + from a conference. It refers to the + notes generated from Take Notes with + Gemini during the conference. + + """ + + http_options = _BaseConferenceRecordsServiceRestTransport._BaseGetSmartNote._get_http_options() + request, metadata = self._interceptor.pre_get_smart_note(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseConferenceRecordsServiceRestTransport._BaseGetSmartNote, + "_BaseGetSmartNote__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2beta.ConferenceRecordsServiceClient.GetSmartNote", + extra={ + "serviceName": "google.apps.meet.v2beta.ConferenceRecordsService", + "rpcName": "GetSmartNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ConferenceRecordsServiceRestTransport._GetSmartNote._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.SmartNote() + pb_resp = resource.SmartNote.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_smart_note(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_smart_note_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.SmartNote.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2beta.ConferenceRecordsServiceClient.get_smart_note", + extra={ + "serviceName": "google.apps.meet.v2beta.ConferenceRecordsService", + "rpcName": "GetSmartNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetTranscript( _BaseConferenceRecordsServiceRestTransport._BaseGetTranscript, ConferenceRecordsServiceRestStub, @@ -2339,6 +2595,154 @@ def __call__( ) return resp + class _ListSmartNotes( + _BaseConferenceRecordsServiceRestTransport._BaseListSmartNotes, + ConferenceRecordsServiceRestStub, + ): + def __hash__(self): + return hash("ConferenceRecordsServiceRestTransport.ListSmartNotes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListSmartNotesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListSmartNotesResponse: + r"""Call the list smart notes method over HTTP. + + Args: + request (~.service.ListSmartNotesRequest): + The request object. Request for ListSmartNotes method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListSmartNotesResponse: + Response for ListSmartNotes method. + """ + + http_options = _BaseConferenceRecordsServiceRestTransport._BaseListSmartNotes._get_http_options() + request, metadata = self._interceptor.pre_list_smart_notes( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseConferenceRecordsServiceRestTransport._BaseListSmartNotes, + "_BaseListSmartNotes__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2beta.ConferenceRecordsServiceClient.ListSmartNotes", + extra={ + "serviceName": "google.apps.meet.v2beta.ConferenceRecordsService", + "rpcName": "ListSmartNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ConferenceRecordsServiceRestTransport._ListSmartNotes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListSmartNotesResponse() + pb_resp = service.ListSmartNotesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_smart_notes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_smart_notes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListSmartNotesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2beta.ConferenceRecordsServiceClient.list_smart_notes", + extra={ + "serviceName": "google.apps.meet.v2beta.ConferenceRecordsService", + "rpcName": "ListSmartNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ListTranscriptEntries( _BaseConferenceRecordsServiceRestTransport._BaseListTranscriptEntries, ConferenceRecordsServiceRestStub, @@ -2670,6 +3074,14 @@ def get_recording( # In C++ this would require a dynamic_cast return self._GetRecording(self._session, self._host, self._interceptor) # type: ignore + @property + def get_smart_note( + self, + ) -> Callable[[service.GetSmartNoteRequest], resource.SmartNote]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSmartNote(self._session, self._host, self._interceptor) # type: ignore + @property def get_transcript( self, @@ -2725,6 +3137,14 @@ def list_recordings( # In C++ this would require a dynamic_cast return self._ListRecordings(self._session, self._host, self._interceptor) # type: ignore + @property + def list_smart_notes( + self, + ) -> Callable[[service.ListSmartNotesRequest], service.ListSmartNotesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSmartNotes(self._session, self._host, self._interceptor) # type: ignore + @property def list_transcript_entries( self, diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest_base.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest_base.py index bfc36a5154e6..fd7e23777956 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest_base.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/transports/rest_base.py @@ -151,6 +151,22 @@ def _get_http_options(): ] return http_options + class _BaseGetSmartNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=conferenceRecords/*/smartNotes/*}", + }, + ] + return http_options + class _BaseGetTranscript: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -245,6 +261,22 @@ def _get_http_options(): ] return http_options + class _BaseListSmartNotes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=conferenceRecords/*}/smartNotes", + }, + ] + return http_options + class _BaseListTranscriptEntries: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/async_client.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/async_client.py index 73deb1129987..fb438ced7239 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/async_client.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/async_client.py @@ -419,7 +419,7 @@ async def get_space( r"""Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. .. code-block:: python @@ -473,7 +473,7 @@ async def sample_get_space(): Meet `__. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -555,7 +555,7 @@ async def update_space( r"""Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. .. code-block:: python @@ -689,7 +689,7 @@ async def connect_active_conference( WebRTC data channels. See `Meet Media API - overview `__ + overview `__ for more details about this connection. .. code-block:: python @@ -748,7 +748,7 @@ async def sample_connect_active_conference(): WebRTC. See [Meet Media API - overview](https://developers.google.com/meet/media-api/guides/overview) + overview](https://developers.google.com/workspace/meet/media-api/guides/overview) for more details about this connection. """ @@ -813,7 +813,7 @@ async def end_active_conference( r"""Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. .. code-block:: python @@ -852,7 +852,7 @@ async def sample_end_active_conference(): sensitive. For example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -921,9 +921,7 @@ async def create_member( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resource.Member: - r"""`Developer - Preview `__: - Create a member. + r"""Creates a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -1045,9 +1043,7 @@ async def get_member( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resource.Member: - r"""`Developer - Preview `__: - Get a member. + r"""Gets a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -1163,9 +1159,7 @@ async def list_members( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListMembersAsyncPager: - r"""`Developer - Preview `__: - List members. + r"""Lists members. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -1294,10 +1288,8 @@ async def delete_member( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: - r"""`Developer - Preview `__: - Delete the member who was previously assigned roles in the - space. + r"""Deletes the member who was previously assigned roles + in the space. .. code-block:: python @@ -1387,6 +1379,220 @@ async def sample_delete_member(): metadata=metadata, ) + async def update_member( + self, + request: Optional[Union[service.UpdateMemberRequest, dict]] = None, + *, + member: Optional[resource.Member] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Updates a member. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + async def sample_update_member(): + # Create a client + client = meet_v2beta.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.UpdateMemberRequest( + ) + + # Make the request + response = await client.update_member(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2beta.types.UpdateMemberRequest, dict]]): + The request object. Request to update a member. + member (:class:`google.apps.meet_v2beta.types.Member`): + Required. The Member to update. + Format: spaces/{space}/members/{member} + + This corresponds to the ``member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask used to specify the fields to be + updated in the member. If update_mask isn't provided(not + set, set with empty paths, or only has "" as paths), it + defaults to update all fields provided with values in + the request. Using "\*" as update_mask will update all + fields, including deleting fields not set in the + request. In case of BatchUpdate, it must be absent or + the same as the update_mask in BatchUpdateMembersRequest + when UpdateMemberRequest is built as a child request of + BatchUpdateMembersRequest. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [member, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMemberRequest): + request = service.UpdateMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if member is not None: + request.member = member + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("member.name", request.member.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_update_members( + self, + request: Optional[Union[service.BatchUpdateMembersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.BatchUpdateMembersResponse: + r"""Updates members of one space within a batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + async def sample_batch_update_members(): + # Create a client + client = meet_v2beta.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_update_members(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.meet_v2beta.types.BatchUpdateMembersRequest, dict]]): + The request object. Request to update members of one + space within a batch. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.types.BatchUpdateMembersResponse: + Response of batch update members. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.BatchUpdateMembersRequest): + request = service.BatchUpdateMembersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_update_members + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "SpacesServiceAsyncClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py index b069f7832a67..dbb54e463900 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py @@ -732,7 +732,7 @@ def get_space( r"""Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. .. code-block:: python @@ -786,7 +786,7 @@ def sample_get_space(): Meet `__. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -865,7 +865,7 @@ def update_space( r"""Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. .. code-block:: python @@ -996,7 +996,7 @@ def connect_active_conference( WebRTC data channels. See `Meet Media API - overview `__ + overview `__ for more details about this connection. .. code-block:: python @@ -1055,7 +1055,7 @@ def sample_connect_active_conference(): WebRTC. See [Meet Media API - overview](https://developers.google.com/meet/media-api/guides/overview) + overview](https://developers.google.com/workspace/meet/media-api/guides/overview) for more details about this connection. """ @@ -1119,7 +1119,7 @@ def end_active_conference( r"""Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. .. code-block:: python @@ -1158,7 +1158,7 @@ def sample_end_active_conference(): sensitive. For example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1224,9 +1224,7 @@ def create_member( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resource.Member: - r"""`Developer - Preview `__: - Create a member. + r"""Creates a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -1345,9 +1343,7 @@ def get_member( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resource.Member: - r"""`Developer - Preview `__: - Get a member. + r"""Gets a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -1460,9 +1456,7 @@ def list_members( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListMembersPager: - r"""`Developer - Preview `__: - List members. + r"""Lists members. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -1588,10 +1582,8 @@ def delete_member( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: - r"""`Developer - Preview `__: - Delete the member who was previously assigned roles in the - space. + r"""Deletes the member who was previously assigned roles + in the space. .. code-block:: python @@ -1678,6 +1670,215 @@ def sample_delete_member(): metadata=metadata, ) + def update_member( + self, + request: Optional[Union[service.UpdateMemberRequest, dict]] = None, + *, + member: Optional[resource.Member] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Updates a member. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + def sample_update_member(): + # Create a client + client = meet_v2beta.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.UpdateMemberRequest( + ) + + # Make the request + response = client.update_member(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2beta.types.UpdateMemberRequest, dict]): + The request object. Request to update a member. + member (google.apps.meet_v2beta.types.Member): + Required. The Member to update. + Format: spaces/{space}/members/{member} + + This corresponds to the ``member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask used to specify the fields to be + updated in the member. If update_mask isn't provided(not + set, set with empty paths, or only has "" as paths), it + defaults to update all fields provided with values in + the request. Using "\*" as update_mask will update all + fields, including deleting fields not set in the + request. In case of BatchUpdate, it must be absent or + the same as the update_mask in BatchUpdateMembersRequest + when UpdateMemberRequest is built as a child request of + BatchUpdateMembersRequest. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.types.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [member, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMemberRequest): + request = service.UpdateMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if member is not None: + request.member = member + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("member.name", request.member.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_members( + self, + request: Optional[Union[service.BatchUpdateMembersRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.BatchUpdateMembersResponse: + r"""Updates members of one space within a batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import meet_v2beta + + def sample_batch_update_members(): + # Create a client + client = meet_v2beta.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_members(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.meet_v2beta.types.BatchUpdateMembersRequest, dict]): + The request object. Request to update members of one + space within a batch. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.meet_v2beta.types.BatchUpdateMembersResponse: + Response of batch update members. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.BatchUpdateMembersRequest): + request = service.BatchUpdateMembersRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_members] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "SpacesServiceClient": return self diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/base.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/base.py index c16092edc082..b3c5af94fc17 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/base.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/base.py @@ -184,7 +184,7 @@ def _prep_wrapped_messages(self, client_info): ), self.create_member: gapic_v1.method.wrap_method( self.create_member, - default_timeout=60.0, + default_timeout=80.0, client_info=client_info, ), self.get_member: gapic_v1.method.wrap_method( @@ -202,6 +202,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.update_member: gapic_v1.method.wrap_method( + self.update_member, + default_timeout=60.0, + client_info=client_info, + ), + self.batch_update_members: gapic_v1.method.wrap_method( + self.batch_update_members, + default_timeout=60.0, + client_info=client_info, + ), } def close(self): @@ -293,6 +303,27 @@ def delete_member( ]: raise NotImplementedError() + @property + def update_member( + self, + ) -> Callable[ + [service.UpdateMemberRequest], + Union[resource.Member, Awaitable[resource.Member]], + ]: + raise NotImplementedError() + + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], + Union[ + service.BatchUpdateMembersResponse, + Awaitable[service.BatchUpdateMembersResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc.py index 9164d466059d..e83873f5a86f 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc.py @@ -357,7 +357,7 @@ def get_space(self) -> Callable[[service.GetSpaceRequest], resource.Space]: Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. Returns: Callable[[~.GetSpaceRequest], @@ -384,7 +384,7 @@ def update_space(self) -> Callable[[service.UpdateSpaceRequest], resource.Space] Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. Returns: Callable[[~.UpdateSpaceRequest], @@ -423,7 +423,7 @@ def connect_active_conference( WebRTC data channels. See `Meet Media API - overview `__ + overview `__ for more details about this connection. Returns: @@ -453,7 +453,7 @@ def end_active_conference( Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. Returns: Callable[[~.EndActiveConferenceRequest], @@ -477,9 +477,7 @@ def end_active_conference( def create_member(self) -> Callable[[service.CreateMemberRequest], resource.Member]: r"""Return a callable for the create member method over gRPC. - `Developer - Preview `__: - Create a member. + Creates a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -508,9 +506,7 @@ def create_member(self) -> Callable[[service.CreateMemberRequest], resource.Memb def get_member(self) -> Callable[[service.GetMemberRequest], resource.Member]: r"""Return a callable for the get member method over gRPC. - `Developer - Preview `__: - Get a member. + Gets a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -541,9 +537,7 @@ def list_members( ) -> Callable[[service.ListMembersRequest], service.ListMembersResponse]: r"""Return a callable for the list members method over gRPC. - `Developer - Preview `__: - List members. + Lists members. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -572,10 +566,8 @@ def list_members( def delete_member(self) -> Callable[[service.DeleteMemberRequest], empty_pb2.Empty]: r"""Return a callable for the delete member method over gRPC. - `Developer - Preview `__: - Delete the member who was previously assigned roles in the - space. + Deletes the member who was previously assigned roles + in the space. Returns: Callable[[~.DeleteMemberRequest], @@ -595,6 +587,58 @@ def delete_member(self) -> Callable[[service.DeleteMemberRequest], empty_pb2.Emp ) return self._stubs["delete_member"] + @property + def update_member(self) -> Callable[[service.UpdateMemberRequest], resource.Member]: + r"""Return a callable for the update member method over gRPC. + + Updates a member. + + Returns: + Callable[[~.UpdateMemberRequest], + ~.Member]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_member" not in self._stubs: + self._stubs["update_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.SpacesService/UpdateMember", + request_serializer=service.UpdateMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["update_member"] + + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], service.BatchUpdateMembersResponse + ]: + r"""Return a callable for the batch update members method over gRPC. + + Updates members of one space within a batch. + + Returns: + Callable[[~.BatchUpdateMembersRequest], + ~.BatchUpdateMembersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_members" not in self._stubs: + self._stubs["batch_update_members"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.SpacesService/BatchUpdateMembers", + request_serializer=service.BatchUpdateMembersRequest.serialize, + response_deserializer=service.BatchUpdateMembersResponse.deserialize, + ) + return self._stubs["batch_update_members"] + def close(self): self._logged_channel.close() diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc_asyncio.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc_asyncio.py index 638ba85bae10..34e5cea7057d 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc_asyncio.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/grpc_asyncio.py @@ -369,7 +369,7 @@ def get_space( Gets details about a meeting space. For an example, see `Get a meeting - space `__. + space `__. Returns: Callable[[~.GetSpaceRequest], @@ -398,7 +398,7 @@ def update_space( Updates details about a meeting space. For an example, see `Update a meeting - space `__. + space `__. Returns: Callable[[~.UpdateSpaceRequest], @@ -437,7 +437,7 @@ def connect_active_conference( WebRTC data channels. See `Meet Media API - overview `__ + overview `__ for more details about this connection. Returns: @@ -467,7 +467,7 @@ def end_active_conference( Ends an active conference (if there's one). For an example, see `End active - conference `__. + conference `__. Returns: Callable[[~.EndActiveConferenceRequest], @@ -493,9 +493,7 @@ def create_member( ) -> Callable[[service.CreateMemberRequest], Awaitable[resource.Member]]: r"""Return a callable for the create member method over gRPC. - `Developer - Preview `__: - Create a member. + Creates a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -526,9 +524,7 @@ def get_member( ) -> Callable[[service.GetMemberRequest], Awaitable[resource.Member]]: r"""Return a callable for the get member method over gRPC. - `Developer - Preview `__: - Get a member. + Gets a member. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -559,9 +555,7 @@ def list_members( ) -> Callable[[service.ListMembersRequest], Awaitable[service.ListMembersResponse]]: r"""Return a callable for the list members method over gRPC. - `Developer - Preview `__: - List members. + Lists members. This API supports the ``fields`` parameter in `SystemParameterContext `__. @@ -592,10 +586,8 @@ def delete_member( ) -> Callable[[service.DeleteMemberRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete member method over gRPC. - `Developer - Preview `__: - Delete the member who was previously assigned roles in the - space. + Deletes the member who was previously assigned roles + in the space. Returns: Callable[[~.DeleteMemberRequest], @@ -615,6 +607,61 @@ def delete_member( ) return self._stubs["delete_member"] + @property + def update_member( + self, + ) -> Callable[[service.UpdateMemberRequest], Awaitable[resource.Member]]: + r"""Return a callable for the update member method over gRPC. + + Updates a member. + + Returns: + Callable[[~.UpdateMemberRequest], + Awaitable[~.Member]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_member" not in self._stubs: + self._stubs["update_member"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.SpacesService/UpdateMember", + request_serializer=service.UpdateMemberRequest.serialize, + response_deserializer=resource.Member.deserialize, + ) + return self._stubs["update_member"] + + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], + Awaitable[service.BatchUpdateMembersResponse], + ]: + r"""Return a callable for the batch update members method over gRPC. + + Updates members of one space within a batch. + + Returns: + Callable[[~.BatchUpdateMembersRequest], + Awaitable[~.BatchUpdateMembersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_members" not in self._stubs: + self._stubs["batch_update_members"] = self._logged_channel.unary_unary( + "/google.apps.meet.v2beta.SpacesService/BatchUpdateMembers", + request_serializer=service.BatchUpdateMembersRequest.serialize, + response_deserializer=service.BatchUpdateMembersResponse.deserialize, + ) + return self._stubs["batch_update_members"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -654,7 +701,7 @@ def _prep_wrapped_messages(self, client_info): ), self.create_member: self._wrap_method( self.create_member, - default_timeout=60.0, + default_timeout=80.0, client_info=client_info, ), self.get_member: self._wrap_method( @@ -672,6 +719,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.update_member: self._wrap_method( + self.update_member, + default_timeout=60.0, + client_info=client_info, + ), + self.batch_update_members: self._wrap_method( + self.batch_update_members, + default_timeout=60.0, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest.py index 4d424489b70b..92671d892cca 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest.py @@ -73,6 +73,14 @@ class SpacesServiceRestInterceptor: .. code-block:: python class MyCustomSpacesServiceInterceptor(SpacesServiceRestInterceptor): + def pre_batch_update_members(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_members(self, response): + logging.log(f"Received response: {response}") + return response + def pre_connect_active_conference(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -129,6 +137,14 @@ def post_list_members(self, response): logging.log(f"Received response: {response}") return response + def pre_update_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_member(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_space(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -143,6 +159,56 @@ def post_update_space(self, response): """ + def pre_batch_update_members( + self, + request: service.BatchUpdateMembersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.BatchUpdateMembersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for batch_update_members + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + + def post_batch_update_members( + self, response: service.BatchUpdateMembersResponse + ) -> service.BatchUpdateMembersResponse: + """Post-rpc interceptor for batch_update_members + + DEPRECATED. Please use the `post_batch_update_members_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SpacesService server but before + it is returned to user code. This `post_batch_update_members` interceptor runs + before the `post_batch_update_members_with_metadata` interceptor. + """ + return response + + def post_batch_update_members_with_metadata( + self, + response: service.BatchUpdateMembersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.BatchUpdateMembersResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for batch_update_members + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SpacesService server but before it is returned to user code. + + We recommend only using this `post_batch_update_members_with_metadata` + interceptor in new development instead of the `post_batch_update_members` interceptor. + When both interceptors are used, this `post_batch_update_members_with_metadata` interceptor runs after the + `post_batch_update_members` interceptor. The (possibly modified) response returned by + `post_batch_update_members` will be passed to + `post_batch_update_members_with_metadata`. + """ + return response, metadata + def pre_connect_active_conference( self, request: service.ConnectActiveConferenceRequest, @@ -441,6 +507,50 @@ def post_list_members_with_metadata( """ return response, metadata + def pre_update_member( + self, + request: service.UpdateMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.UpdateMemberRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the SpacesService server. + """ + return request, metadata + + def post_update_member(self, response: resource.Member) -> resource.Member: + """Post-rpc interceptor for update_member + + DEPRECATED. Please use the `post_update_member_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SpacesService server but before + it is returned to user code. This `post_update_member` interceptor runs + before the `post_update_member_with_metadata` interceptor. + """ + return response + + def post_update_member_with_metadata( + self, + response: resource.Member, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resource.Member, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_member + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SpacesService server but before it is returned to user code. + + We recommend only using this `post_update_member_with_metadata` + interceptor in new development instead of the `post_update_member` interceptor. + When both interceptors are used, this `post_update_member_with_metadata` interceptor runs after the + `post_update_member` interceptor. The (possibly modified) response returned by + `post_update_member` will be passed to + `post_update_member_with_metadata`. + """ + return response, metadata + def pre_update_space( self, request: service.UpdateSpaceRequest, @@ -579,6 +689,156 @@ def __init__( self._interceptor = interceptor or SpacesServiceRestInterceptor() self._prep_wrapped_messages(client_info) + class _BatchUpdateMembers( + _BaseSpacesServiceRestTransport._BaseBatchUpdateMembers, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.BatchUpdateMembers") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.BatchUpdateMembersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.BatchUpdateMembersResponse: + r"""Call the batch update members method over HTTP. + + Args: + request (~.service.BatchUpdateMembersRequest): + The request object. Request to update members of one + space within a batch. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.BatchUpdateMembersResponse: + Response of batch update members. + """ + + http_options = _BaseSpacesServiceRestTransport._BaseBatchUpdateMembers._get_http_options() + request, metadata = self._interceptor.pre_batch_update_members( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseBatchUpdateMembers, + "_BaseBatchUpdateMembers__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2beta.SpacesServiceClient.BatchUpdateMembers", + extra={ + "serviceName": "google.apps.meet.v2beta.SpacesService", + "rpcName": "BatchUpdateMembers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._BatchUpdateMembers._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.BatchUpdateMembersResponse() + pb_resp = service.BatchUpdateMembersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_members(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_update_members_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.BatchUpdateMembersResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2beta.SpacesServiceClient.batch_update_members", + extra={ + "serviceName": "google.apps.meet.v2beta.SpacesService", + "rpcName": "BatchUpdateMembers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ConnectActiveConference( _BaseSpacesServiceRestTransport._BaseConnectActiveConference, SpacesServiceRestStub, @@ -641,7 +901,7 @@ def __call__( WebRTC. See `Meet Media API - overview `__ + overview `__ for more details about this connection. """ @@ -1703,6 +1963,156 @@ def __call__( ) return resp + class _UpdateMember( + _BaseSpacesServiceRestTransport._BaseUpdateMember, SpacesServiceRestStub + ): + def __hash__(self): + return hash("SpacesServiceRestTransport.UpdateMember") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.UpdateMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resource.Member: + r"""Call the update member method over HTTP. + + Args: + request (~.service.UpdateMemberRequest): + The request object. Request to update a member. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resource.Member: + Users who are configured to have a + role in the space. These users can join + the space without knocking. + + """ + + http_options = ( + _BaseSpacesServiceRestTransport._BaseUpdateMember._get_http_options() + ) + request, metadata = self._interceptor.pre_update_member(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSpacesServiceRestTransport._BaseUpdateMember, + "_BaseUpdateMember__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.apps.meet_v2beta.SpacesServiceClient.UpdateMember", + extra={ + "serviceName": "google.apps.meet.v2beta.SpacesService", + "rpcName": "UpdateMember", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SpacesServiceRestTransport._UpdateMember._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource.Member() + pb_resp = resource.Member.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_member(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_member_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resource.Member.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.apps.meet_v2beta.SpacesServiceClient.update_member", + extra={ + "serviceName": "google.apps.meet.v2beta.SpacesService", + "rpcName": "UpdateMember", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateSpace( _BaseSpacesServiceRestTransport._BaseUpdateSpace, SpacesServiceRestStub ): @@ -1853,6 +2263,16 @@ def __call__( ) return resp + @property + def batch_update_members( + self, + ) -> Callable[ + [service.BatchUpdateMembersRequest], service.BatchUpdateMembersResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdateMembers(self._session, self._host, self._interceptor) # type: ignore + @property def connect_active_conference( self, @@ -1912,6 +2332,12 @@ def list_members( # In C++ this would require a dynamic_cast return self._ListMembers(self._session, self._host, self._interceptor) # type: ignore + @property + def update_member(self) -> Callable[[service.UpdateMemberRequest], resource.Member]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMember(self._session, self._host, self._interceptor) # type: ignore + @property def update_space(self) -> Callable[[service.UpdateSpaceRequest], resource.Space]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest_base.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest_base.py index 5040c2cf7ef6..d6d86ca065ff 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest_base.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/transports/rest_base.py @@ -88,6 +88,23 @@ def __init__( api_audience=api_audience, ) + class _BaseBatchUpdateMembers: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=spaces/*}/members:batchUpdate", + "body": "*", + }, + ] + return http_options + class _BaseConnectActiveConference: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -218,6 +235,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{member.name=spaces/*/members/*}", + "body": "member", + }, + ] + return http_options + class _BaseUpdateSpace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/types/__init__.py b/packages/google-apps-meet/google/apps/meet_v2beta/types/__init__.py index c07ab468b592..e4075dce6702 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/types/__init__.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/types/__init__.py @@ -25,12 +25,15 @@ PhoneUser, Recording, SignedinUser, + SmartNote, Space, SpaceConfig, Transcript, TranscriptEntry, ) from .service import ( + BatchUpdateMembersRequest, + BatchUpdateMembersResponse, ConnectActiveConferenceRequest, ConnectActiveConferenceResponse, CreateMemberRequest, @@ -42,6 +45,7 @@ GetParticipantRequest, GetParticipantSessionRequest, GetRecordingRequest, + GetSmartNoteRequest, GetSpaceRequest, GetTranscriptEntryRequest, GetTranscriptRequest, @@ -55,10 +59,13 @@ ListParticipantsResponse, ListRecordingsRequest, ListRecordingsResponse, + ListSmartNotesRequest, + ListSmartNotesResponse, ListTranscriptEntriesRequest, ListTranscriptEntriesResponse, ListTranscriptsRequest, ListTranscriptsResponse, + UpdateMemberRequest, UpdateSpaceRequest, ) @@ -74,10 +81,13 @@ "PhoneUser", "Recording", "SignedinUser", + "SmartNote", "Space", "SpaceConfig", "Transcript", "TranscriptEntry", + "BatchUpdateMembersRequest", + "BatchUpdateMembersResponse", "ConnectActiveConferenceRequest", "ConnectActiveConferenceResponse", "CreateMemberRequest", @@ -89,6 +99,7 @@ "GetParticipantRequest", "GetParticipantSessionRequest", "GetRecordingRequest", + "GetSmartNoteRequest", "GetSpaceRequest", "GetTranscriptEntryRequest", "GetTranscriptRequest", @@ -102,9 +113,12 @@ "ListParticipantsResponse", "ListRecordingsRequest", "ListRecordingsResponse", + "ListSmartNotesRequest", + "ListSmartNotesResponse", "ListTranscriptEntriesRequest", "ListTranscriptEntriesResponse", "ListTranscriptsRequest", "ListTranscriptsResponse", + "UpdateMemberRequest", "UpdateSpaceRequest", ) diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/types/resource.py b/packages/google-apps-meet/google/apps/meet_v2beta/types/resource.py index b6a8f969e4eb..df861dcbd276 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/types/resource.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/types/resource.py @@ -38,6 +38,7 @@ "Transcript", "DocsDestination", "TranscriptEntry", + "SmartNote", }, ) @@ -57,7 +58,7 @@ class Space(proto.Message): example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. meeting_uri (str): Output only. URI used to join meetings consisting of ``https://meet.google.com/`` followed by the @@ -79,8 +80,90 @@ class Space(proto.Message): space. active_conference (google.apps.meet_v2beta.types.ActiveConference): Active conference, if it exists. + phone_access (MutableSequence[google.apps.meet_v2beta.types.Space.PhoneAccess]): + Output only. All regional phone access + methods for this meeting space. Can be empty. + gateway_sip_access (MutableSequence[google.apps.meet_v2beta.types.Space.GatewaySipAccess]): + Output only. The SIP-based access methods + that can be used to join the conference. Can be + empty. """ + class PhoneAccess(proto.Message): + r"""Phone access contains information required to dial into a + conference using a regional phone number and a PIN that is + specific to that phone number. + + Attributes: + phone_number (str): + The phone number to dial for this meeting + space in E.164 format. Full phone number with a + leading '+' character. + pin (str): + The PIN that users must enter after dialing + the given number. The PIN consists of only + decimal digits and the length may vary. + region_code (str): + The CLDR/ISO 3166 region code for the country + associated with this phone access. To be parsed + by the i18n RegionCode utility. Example: "SE" + for Sweden. + language_code (str): + The BCP 47/LDML language code for the + language associated with this phone access. To + be parsed by the i18n LanguageCode utility. + Examples: "es-419" for Latin American Spanish, + "fr-CA" for Canadian French. + """ + + phone_number: str = proto.Field( + proto.STRING, + number=1, + ) + pin: str = proto.Field( + proto.STRING, + number=2, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + + class GatewaySipAccess(proto.Message): + r"""Details how to join the conference through a SIP gateway. + + Attributes: + uri (str): + The Session Initiation Protocol (SIP) URI the conference can + be reached through. + + The string is in one of these formats: + + - "sip:USER_ID@GATEWAY_ADDRESS" + - "sips:USER_ID@GATEWAY_ADDRESS" + + where USER_ID is the 13-digit universal pin (with the future + option to support using a Meet meeting code as well), and + GATEWAY_ADDRESS is a valid address to be resolved using a + DNS SRV lookup, or a dotted quad. + sip_access_code (str): + The permanent numeric code for manual entry + on specially configured devices. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + sip_access_code: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -103,6 +186,16 @@ class Space(proto.Message): number=6, message="ActiveConference", ) + phone_access: MutableSequence[PhoneAccess] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=PhoneAccess, + ) + gateway_sip_access: MutableSequence[GatewaySipAccess] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=GatewaySipAccess, + ) class ActiveConference(proto.Message): @@ -114,12 +207,19 @@ class ActiveConference(proto.Message): Format: ``conferenceRecords/{conference_record}`` where ``{conference_record}`` is a unique ID for each instance of a call within a space. + media_api_consenter_present (bool): + Output only. Indicates whether a media api + consenter is present in the conference. """ conference_record: str = proto.Field( proto.STRING, number=1, ) + media_api_consenter_present: bool = proto.Field( + proto.BOOL, + number=2, + ) class SpaceConfig(proto.Message): @@ -137,25 +237,21 @@ class SpaceConfig(proto.Message): join meetings hosted in this meeting space. Default: EntryPointAccess.ALL moderation (google.apps.meet_v2beta.types.SpaceConfig.Moderation): - `Developer - Preview `__: - The pre-configured moderation mode for the Meeting. Default: - Controlled by the user's policies. + The pre-configured moderation mode for the + Meeting. Default: Controlled by the user's + policies. moderation_restrictions (google.apps.meet_v2beta.types.SpaceConfig.ModerationRestrictions): - `Developer - Preview `__: - When moderation.ON, these restrictions go into effect for - the meeting. When moderation.OFF, will be reset to default + When moderation.ON, these restrictions go + into effect for the meeting. When + moderation.OFF, will be reset to default ModerationRestrictions. attendance_report_generation_type (google.apps.meet_v2beta.types.SpaceConfig.AttendanceReportGenerationType): - `Developer - Preview `__: - Whether attendance report is enabled for the meeting space. + Whether attendance report is enabled for the + meeting space. artifact_config (google.apps.meet_v2beta.types.SpaceConfig.ArtifactConfig): - `Developer - Preview `__: - Configuration pertaining to the auto-generated artifacts - that the meeting supports. + Configuration pertaining to the + auto-generated artifacts that the meeting + supports. """ class AccessType(proto.Enum): @@ -396,9 +492,9 @@ class TranscriptionConfig(proto.Message): ) class SmartNotesConfig(proto.Message): - r"""Configuration related to smart notes in a meeting space. More - details about smart notes - https://support.google.com/meet/answer/14754931?hl=en. + r"""Configuration related to smart notes in a meeting space. For more + information about smart notes, see `"Take notes for me" in Google + Meet `__. Attributes: auto_smart_notes_generation (google.apps.meet_v2beta.types.SpaceConfig.ArtifactConfig.AutoGenerationType): @@ -492,13 +588,12 @@ class Role(proto.Enum): Values: ROLE_UNSPECIFIED (0): - This is used to indicate the user hasn't - specified any value and the user’s role will be - determined upon joining the meetings between - 'contributor' and 'viewer' role depending on - meeting configuration. More details about viewer - role - https://support.google.com/meet/answer/13658394?hl=en. + This is used to indicate the user hasn't specified any value + and the user’s role will be determined upon joining the + meetings between 'contributor' and 'viewer' role depending + on meeting configuration. For more information about the + viewer role, see `Assign View only roles in Google + Meet `__. COHOST (1): Co-host role. """ @@ -1002,4 +1097,82 @@ class TranscriptEntry(proto.Message): ) +class SmartNote(proto.Message): + r"""Metadata for a smart note generated from a conference. It + refers to the notes generated from Take Notes with Gemini during + the conference. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + docs_destination (google.apps.meet_v2beta.types.DocsDestination): + Output only. The Google Doc destination where + the smart notes are saved. + + This field is a member of `oneof`_ ``destination``. + name (str): + Output only. Identifier. Resource name of the smart notes. + Format: + ``conferenceRecords/{conference_record}/smartNotes/{smart_note}``, + where ``{smart_note}`` is a 1:1 mapping to each unique smart + notes session of the conference. + state (google.apps.meet_v2beta.types.SmartNote.State): + Output only. Current state. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the smart notes + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the smart notes + stopped. + """ + + class State(proto.Enum): + r"""Current state of the smart notes session. + + Values: + STATE_UNSPECIFIED (0): + Default, never used. + STARTED (1): + An active smart notes session has started. + ENDED (2): + This smart notes session has ended, but the + smart notes file hasn't been generated yet. + FILE_GENERATED (3): + Smart notes file is generated and ready to + download. + """ + + STATE_UNSPECIFIED = 0 + STARTED = 1 + ENDED = 2 + FILE_GENERATED = 3 + + docs_destination: "DocsDestination" = proto.Field( + proto.MESSAGE, + number=5, + oneof="destination", + message="DocsDestination", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/types/service.py b/packages/google-apps-meet/google/apps/meet_v2beta/types/service.py index 15f334f31871..afa5a97eb65d 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/types/service.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/types/service.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import proto # type: ignore @@ -36,6 +37,9 @@ "ListMembersRequest", "ListMembersResponse", "DeleteMemberRequest", + "UpdateMemberRequest", + "BatchUpdateMembersRequest", + "BatchUpdateMembersResponse", "GetConferenceRecordRequest", "ListConferenceRecordsRequest", "ListConferenceRecordsResponse", @@ -54,6 +58,9 @@ "GetTranscriptEntryRequest", "ListTranscriptEntriesRequest", "ListTranscriptEntriesResponse", + "GetSmartNoteRequest", + "ListSmartNotesRequest", + "ListSmartNotesResponse", }, ) @@ -102,7 +109,7 @@ class GetSpaceRequest(proto.Message): Meet `__. For more information, see `How Meet identifies a meeting - space `__. + space `__. """ name: str = proto.Field( @@ -156,8 +163,30 @@ class ConnectActiveConferenceRequest(proto.Message): 8829 `__. This is the standard SDP format generated by a peer connection's createOffer() and createAnswer() methods. + config (google.apps.meet_v2beta.types.ConnectActiveConferenceRequest.ConnectionConfig): + Optional. Additional configuration options + for a Media API session. If unset, default + values will be provided for the session. """ + class ConnectionConfig(proto.Message): + r"""Additional configuration options for Media API sessions. + + Attributes: + confirmation_timeout (google.protobuf.duration_pb2.Duration): + Optional. The amount of time to wait before a + confirmation action is cancelled. If unset, a + default value will be used. The duration cannot + exceed 5 minutes. Larger timeouts and negative + durations will result in RPC failure. + """ + + confirmation_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -166,6 +195,11 @@ class ConnectActiveConferenceRequest(proto.Message): proto.STRING, number=2, ) + config: ConnectionConfig = proto.Field( + proto.MESSAGE, + number=3, + message=ConnectionConfig, + ) class ConnectActiveConferenceResponse(proto.Message): @@ -175,7 +209,7 @@ class ConnectActiveConferenceResponse(proto.Message): further communication must occur across WebRTC. See `Meet Media API - overview `__ + overview `__ for more details about this connection. Attributes: @@ -210,7 +244,7 @@ class EndActiveConferenceRequest(proto.Message): example, ``jQCFfuBOdN5z``. For more information, see `How Meet identifies a meeting - space `__. + space `__. """ name: str = proto.Field( @@ -264,10 +298,10 @@ class ListMembersRequest(proto.Message): page_size (int): Optional. Maximum number of members to return. The service might return fewer than this - value. If unspecified, at most 25 members are - returned. The maximum value is 100; values above - 100 are coerced to 100. Maximum might change in - the future. + value. If unspecified or set to 0, at most 250 + members are returned. The maximum value is 500; + values above 500 are coerced to 500. Maximum + might change in the future. page_token (str): Optional. Page token returned from previous List Call. @@ -329,6 +363,107 @@ class DeleteMemberRequest(proto.Message): ) +class UpdateMemberRequest(proto.Message): + r"""Request to update a member. + + Attributes: + member (google.apps.meet_v2beta.types.Member): + Required. The Member to update. + Format: spaces/{space}/members/{member} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask used to specify the fields to be + updated in the member. If update_mask isn't provided(not + set, set with empty paths, or only has "" as paths), it + defaults to update all fields provided with values in the + request. Using "\*" as update_mask will update all fields, + including deleting fields not set in the request. In case of + BatchUpdate, it must be absent or the same as the + update_mask in BatchUpdateMembersRequest when + UpdateMemberRequest is built as a child request of + BatchUpdateMembersRequest. + """ + + member: resource.Member = proto.Field( + proto.MESSAGE, + number=1, + message=resource.Member, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateMembersRequest(proto.Message): + r"""Request to update members of one space within a batch. + + Attributes: + parent (str): + Required. The parent resource shared by all + Members being updated. Format: spaces/{space} + requests (MutableSequence[google.apps.meet_v2beta.types.UpdateMemberRequest]): + Required. The request message specifying the + resources to update. A maximum of 500 members + can be modified in a batch. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Top-level field mask used to + specify the fields to be updated in the member + for all UpdateMemberRequests. There are 4 + possible scenarios for top-level and child field + mask: + + 1. top-level and child field mask is absent: + + All fields provided in the requests are + updated, including deleting fields not set in + the requests. + 2. top-level field mask is present but child + field mask is absent: + + The fields specified in the top-level field + mask are updated. + 3. top-level and child field mask is present: + + The child field mask must be the same as the + top-level field mask. + 4. top-level field mask is absent but child + field mask is present: + + It isn't supported and will return an error. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["UpdateMemberRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="UpdateMemberRequest", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateMembersResponse(proto.Message): + r"""Response of batch update members. + + Attributes: + members (MutableSequence[google.apps.meet_v2beta.types.Member]): + Members updated. + """ + + members: MutableSequence[resource.Member] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resource.Member, + ) + + class GetConferenceRecordRequest(proto.Message): r"""Request to get a conference record. @@ -827,4 +962,79 @@ def raw_page(self): ) +class GetSmartNoteRequest(proto.Message): + r"""Request for GetSmartNote method. + + Attributes: + name (str): + Required. Resource name of the smart note. Format: + conferenceRecords/{conference_record}/smartNotes/{smart_note} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSmartNotesRequest(proto.Message): + r"""Request for ListSmartNotes method. + + Attributes: + parent (str): + Required. Format: ``conferenceRecords/{conference_record}`` + page_size (int): + Optional. Maximum number of smart notes to + return. The service might return fewer than this + value. If unspecified, at most 10 smart notes + are returned. The maximum value is 100; values + above 100 are coerced to 100. Maximum might + change in the future. + page_token (str): + Optional. Page token returned from previous + List Call. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSmartNotesResponse(proto.Message): + r"""Response for ListSmartNotes method. + + Attributes: + smart_notes (MutableSequence[google.apps.meet_v2beta.types.SmartNote]): + List of smart notes in one page. + next_page_token (str): + Token to be circulated back for further List + call if current List doesn't include all the + smart notes. Unset if all smart notes are + returned. + """ + + @property + def raw_page(self): + return self + + smart_notes: MutableSequence[resource.SmartNote] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resource.SmartNote, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_get_smart_note_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_get_smart_note_async.py new file mode 100644 index 000000000000..d0100adb1680 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_get_smart_note_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSmartNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_ConferenceRecordsService_GetSmartNote_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_get_smart_note(): + # Create a client + client = meet_v2.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_smart_note(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_ConferenceRecordsService_GetSmartNote_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_get_smart_note_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_get_smart_note_sync.py new file mode 100644 index 000000000000..7b2bf876fede --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_get_smart_note_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSmartNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_ConferenceRecordsService_GetSmartNote_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_get_smart_note(): + # Create a client + client = meet_v2.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_smart_note(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_ConferenceRecordsService_GetSmartNote_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_list_smart_notes_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_list_smart_notes_async.py new file mode 100644 index 000000000000..5b74b9a91527 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_list_smart_notes_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSmartNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_ConferenceRecordsService_ListSmartNotes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_list_smart_notes(): + # Create a client + client = meet_v2.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END meet_v2_generated_ConferenceRecordsService_ListSmartNotes_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_list_smart_notes_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_list_smart_notes_sync.py new file mode 100644 index 000000000000..d287a44e3f40 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_conference_records_service_list_smart_notes_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSmartNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_ConferenceRecordsService_ListSmartNotes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_list_smart_notes(): + # Create a client + client = meet_v2.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END meet_v2_generated_ConferenceRecordsService_ListSmartNotes_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_batch_update_members_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_batch_update_members_async.py new file mode 100644 index 000000000000..a3fdb687e9aa --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_batch_update_members_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchUpdateMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_BatchUpdateMembers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_batch_update_members(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_update_members(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_BatchUpdateMembers_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_batch_update_members_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_batch_update_members_sync.py new file mode 100644 index 000000000000..4429394b3f03 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_batch_update_members_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchUpdateMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_BatchUpdateMembers_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_batch_update_members(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_members(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_BatchUpdateMembers_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_create_member_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_create_member_async.py new file mode 100644 index 000000000000..2b8b4b38b662 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_create_member_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_CreateMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_create_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.CreateMemberRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_CreateMember_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_create_member_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_create_member_sync.py new file mode 100644 index 000000000000..ae7109e3b14c --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_create_member_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_CreateMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_create_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.CreateMemberRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_CreateMember_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_delete_member_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_delete_member_async.py new file mode 100644 index 000000000000..1e8b61044509 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_delete_member_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_DeleteMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_delete_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.DeleteMemberRequest( + name="name_value", + ) + + # Make the request + await client.delete_member(request=request) + + +# [END meet_v2_generated_SpacesService_DeleteMember_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_delete_member_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_delete_member_sync.py new file mode 100644 index 000000000000..fa56cb0f6e7d --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_delete_member_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_DeleteMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_delete_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.DeleteMemberRequest( + name="name_value", + ) + + # Make the request + client.delete_member(request=request) + + +# [END meet_v2_generated_SpacesService_DeleteMember_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_get_member_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_get_member_async.py new file mode 100644 index 000000000000..5b09a74439ea --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_get_member_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_GetMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_get_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.GetMemberRequest( + name="name_value", + ) + + # Make the request + response = await client.get_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_GetMember_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_get_member_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_get_member_sync.py new file mode 100644 index 000000000000..a9b4d053a649 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_get_member_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_GetMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_get_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.GetMemberRequest( + name="name_value", + ) + + # Make the request + response = client.get_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_GetMember_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_list_members_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_list_members_async.py new file mode 100644 index 000000000000..5e4d208b7243 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_list_members_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_ListMembers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_list_members(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.ListMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_members(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END meet_v2_generated_SpacesService_ListMembers_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_list_members_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_list_members_sync.py new file mode 100644 index 000000000000..210466a3bb40 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_list_members_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_ListMembers_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_list_members(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.ListMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_members(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END meet_v2_generated_SpacesService_ListMembers_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_update_member_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_update_member_async.py new file mode 100644 index 000000000000..ad738e100ccf --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_update_member_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_UpdateMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +async def sample_update_member(): + # Create a client + client = meet_v2.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2.UpdateMemberRequest() + + # Make the request + response = await client.update_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_UpdateMember_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_update_member_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_update_member_sync.py new file mode 100644 index 000000000000..cf6f82b0ebe2 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2_generated_spaces_service_update_member_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2_generated_SpacesService_UpdateMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2 + + +def sample_update_member(): + # Create a client + client = meet_v2.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2.UpdateMemberRequest() + + # Make the request + response = client.update_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2_generated_SpacesService_UpdateMember_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_get_smart_note_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_get_smart_note_async.py new file mode 100644 index 000000000000..9119d9932aaf --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_get_smart_note_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSmartNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_ConferenceRecordsService_GetSmartNote_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +async def sample_get_smart_note(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_smart_note(request=request) + + # Handle the response + print(response) + + +# [END meet_v2beta_generated_ConferenceRecordsService_GetSmartNote_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_get_smart_note_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_get_smart_note_sync.py new file mode 100644 index 000000000000..128ba0719fcf --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_get_smart_note_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSmartNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_ConferenceRecordsService_GetSmartNote_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +def sample_get_smart_note(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.GetSmartNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_smart_note(request=request) + + # Handle the response + print(response) + + +# [END meet_v2beta_generated_ConferenceRecordsService_GetSmartNote_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_list_smart_notes_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_list_smart_notes_async.py new file mode 100644 index 000000000000..48117459508f --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_list_smart_notes_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSmartNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_ConferenceRecordsService_ListSmartNotes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +async def sample_list_smart_notes(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END meet_v2beta_generated_ConferenceRecordsService_ListSmartNotes_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_list_smart_notes_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_list_smart_notes_sync.py new file mode 100644 index 000000000000..a4c7c8098b29 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_conference_records_service_list_smart_notes_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSmartNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_ConferenceRecordsService_ListSmartNotes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +def sample_list_smart_notes(): + # Create a client + client = meet_v2beta.ConferenceRecordsServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.ListSmartNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_smart_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END meet_v2beta_generated_ConferenceRecordsService_ListSmartNotes_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_batch_update_members_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_batch_update_members_async.py new file mode 100644 index 000000000000..e9cb21bea399 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_batch_update_members_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchUpdateMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_SpacesService_BatchUpdateMembers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +async def sample_batch_update_members(): + # Create a client + client = meet_v2beta.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_update_members(request=request) + + # Handle the response + print(response) + + +# [END meet_v2beta_generated_SpacesService_BatchUpdateMembers_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_batch_update_members_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_batch_update_members_sync.py new file mode 100644 index 000000000000..ee938893e1d3 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_batch_update_members_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchUpdateMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_SpacesService_BatchUpdateMembers_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +def sample_batch_update_members(): + # Create a client + client = meet_v2beta.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_members(request=request) + + # Handle the response + print(response) + + +# [END meet_v2beta_generated_SpacesService_BatchUpdateMembers_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_update_member_async.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_update_member_async.py new file mode 100644 index 000000000000..47ee6d61ec86 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_update_member_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_SpacesService_UpdateMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +async def sample_update_member(): + # Create a client + client = meet_v2beta.SpacesServiceAsyncClient() + + # Initialize request argument(s) + request = meet_v2beta.UpdateMemberRequest() + + # Make the request + response = await client.update_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2beta_generated_SpacesService_UpdateMember_async] diff --git a/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_update_member_sync.py b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_update_member_sync.py new file mode 100644 index 000000000000..d8b080f31261 --- /dev/null +++ b/packages/google-apps-meet/samples/generated_samples/meet_v2beta_generated_spaces_service_update_member_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-meet + + +# [START meet_v2beta_generated_SpacesService_UpdateMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import meet_v2beta + + +def sample_update_member(): + # Create a client + client = meet_v2beta.SpacesServiceClient() + + # Initialize request argument(s) + request = meet_v2beta.UpdateMemberRequest() + + # Make the request + response = client.update_member(request=request) + + # Handle the response + print(response) + + +# [END meet_v2beta_generated_SpacesService_UpdateMember_sync] diff --git a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json index 89db5b051ea8..5441e4315100 100644 --- a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json +++ b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-apps-meet", - "version": "0.5.0" + "version": "0.5.1" }, "snippets": [ { @@ -655,6 +655,167 @@ ], "title": "meet_v2_generated_conference_records_service_get_recording_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient", + "shortName": "ConferenceRecordsServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient.get_smart_note", + "method": { + "fullName": "google.apps.meet.v2.ConferenceRecordsService.GetSmartNote", + "service": { + "fullName": "google.apps.meet.v2.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "GetSmartNote" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.GetSmartNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.SmartNote", + "shortName": "get_smart_note" + }, + "description": "Sample for GetSmartNote", + "file": "meet_v2_generated_conference_records_service_get_smart_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_ConferenceRecordsService_GetSmartNote_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_conference_records_service_get_smart_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient", + "shortName": "ConferenceRecordsServiceClient" + }, + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient.get_smart_note", + "method": { + "fullName": "google.apps.meet.v2.ConferenceRecordsService.GetSmartNote", + "service": { + "fullName": "google.apps.meet.v2.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "GetSmartNote" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.GetSmartNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.SmartNote", + "shortName": "get_smart_note" + }, + "description": "Sample for GetSmartNote", + "file": "meet_v2_generated_conference_records_service_get_smart_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_ConferenceRecordsService_GetSmartNote_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_conference_records_service_get_smart_note_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1621,19 +1782,19 @@ "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient", "shortName": "ConferenceRecordsServiceAsyncClient" }, - "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient.list_transcript_entries", + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient.list_smart_notes", "method": { - "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscriptEntries", + "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListSmartNotes", "service": { "fullName": "google.apps.meet.v2.ConferenceRecordsService", "shortName": "ConferenceRecordsService" }, - "shortName": "ListTranscriptEntries" + "shortName": "ListSmartNotes" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.ListTranscriptEntriesRequest" + "type": "google.apps.meet_v2.types.ListSmartNotesRequest" }, { "name": "parent", @@ -1652,14 +1813,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptEntriesAsyncPager", - "shortName": "list_transcript_entries" + "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListSmartNotesAsyncPager", + "shortName": "list_smart_notes" }, - "description": "Sample for ListTranscriptEntries", - "file": "meet_v2_generated_conference_records_service_list_transcript_entries_async.py", + "description": "Sample for ListSmartNotes", + "file": "meet_v2_generated_conference_records_service_list_smart_notes_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscriptEntries_async", + "regionTag": "meet_v2_generated_ConferenceRecordsService_ListSmartNotes_async", "segments": [ { "end": 52, @@ -1692,7 +1853,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_conference_records_service_list_transcript_entries_async.py" + "title": "meet_v2_generated_conference_records_service_list_smart_notes_async.py" }, { "canonical": true, @@ -1701,19 +1862,19 @@ "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient", "shortName": "ConferenceRecordsServiceClient" }, - "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient.list_transcript_entries", + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient.list_smart_notes", "method": { - "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscriptEntries", + "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListSmartNotes", "service": { "fullName": "google.apps.meet.v2.ConferenceRecordsService", "shortName": "ConferenceRecordsService" }, - "shortName": "ListTranscriptEntries" + "shortName": "ListSmartNotes" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.ListTranscriptEntriesRequest" + "type": "google.apps.meet_v2.types.ListSmartNotesRequest" }, { "name": "parent", @@ -1732,14 +1893,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptEntriesPager", - "shortName": "list_transcript_entries" + "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListSmartNotesPager", + "shortName": "list_smart_notes" }, - "description": "Sample for ListTranscriptEntries", - "file": "meet_v2_generated_conference_records_service_list_transcript_entries_sync.py", + "description": "Sample for ListSmartNotes", + "file": "meet_v2_generated_conference_records_service_list_smart_notes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscriptEntries_sync", + "regionTag": "meet_v2_generated_ConferenceRecordsService_ListSmartNotes_sync", "segments": [ { "end": 52, @@ -1772,7 +1933,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_conference_records_service_list_transcript_entries_sync.py" + "title": "meet_v2_generated_conference_records_service_list_smart_notes_sync.py" }, { "canonical": true, @@ -1782,19 +1943,19 @@ "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient", "shortName": "ConferenceRecordsServiceAsyncClient" }, - "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient.list_transcripts", + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient.list_transcript_entries", "method": { - "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscripts", + "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscriptEntries", "service": { "fullName": "google.apps.meet.v2.ConferenceRecordsService", "shortName": "ConferenceRecordsService" }, - "shortName": "ListTranscripts" + "shortName": "ListTranscriptEntries" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.ListTranscriptsRequest" + "type": "google.apps.meet_v2.types.ListTranscriptEntriesRequest" }, { "name": "parent", @@ -1813,14 +1974,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptsAsyncPager", - "shortName": "list_transcripts" + "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptEntriesAsyncPager", + "shortName": "list_transcript_entries" }, - "description": "Sample for ListTranscripts", - "file": "meet_v2_generated_conference_records_service_list_transcripts_async.py", + "description": "Sample for ListTranscriptEntries", + "file": "meet_v2_generated_conference_records_service_list_transcript_entries_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscripts_async", + "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscriptEntries_async", "segments": [ { "end": 52, @@ -1853,7 +2014,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_conference_records_service_list_transcripts_async.py" + "title": "meet_v2_generated_conference_records_service_list_transcript_entries_async.py" }, { "canonical": true, @@ -1862,19 +2023,19 @@ "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient", "shortName": "ConferenceRecordsServiceClient" }, - "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient.list_transcripts", + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient.list_transcript_entries", "method": { - "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscripts", + "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscriptEntries", "service": { "fullName": "google.apps.meet.v2.ConferenceRecordsService", "shortName": "ConferenceRecordsService" }, - "shortName": "ListTranscripts" + "shortName": "ListTranscriptEntries" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.ListTranscriptsRequest" + "type": "google.apps.meet_v2.types.ListTranscriptEntriesRequest" }, { "name": "parent", @@ -1893,14 +2054,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptsPager", - "shortName": "list_transcripts" + "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptEntriesPager", + "shortName": "list_transcript_entries" }, - "description": "Sample for ListTranscripts", - "file": "meet_v2_generated_conference_records_service_list_transcripts_sync.py", + "description": "Sample for ListTranscriptEntries", + "file": "meet_v2_generated_conference_records_service_list_transcript_entries_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscripts_sync", + "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscriptEntries_sync", "segments": [ { "end": 52, @@ -1933,33 +2094,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_conference_records_service_list_transcripts_sync.py" + "title": "meet_v2_generated_conference_records_service_list_transcript_entries_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", - "shortName": "SpacesServiceAsyncClient" + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient", + "shortName": "ConferenceRecordsServiceAsyncClient" }, - "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.create_space", + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceAsyncClient.list_transcripts", "method": { - "fullName": "google.apps.meet.v2.SpacesService.CreateSpace", + "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscripts", "service": { - "fullName": "google.apps.meet.v2.SpacesService", - "shortName": "SpacesService" + "fullName": "google.apps.meet.v2.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" }, - "shortName": "CreateSpace" + "shortName": "ListTranscripts" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.CreateSpaceRequest" + "type": "google.apps.meet_v2.types.ListTranscriptsRequest" }, { - "name": "space", - "type": "google.apps.meet_v2.types.Space" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -1974,22 +2135,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.types.Space", - "shortName": "create_space" + "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptsAsyncPager", + "shortName": "list_transcripts" }, - "description": "Sample for CreateSpace", - "file": "meet_v2_generated_spaces_service_create_space_async.py", + "description": "Sample for ListTranscripts", + "file": "meet_v2_generated_conference_records_service_list_transcripts_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_SpacesService_CreateSpace_async", + "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscripts_async", "segments": [ { - "end": 50, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1999,47 +2160,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_spaces_service_create_space_async.py" + "title": "meet_v2_generated_conference_records_service_list_transcripts_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.apps.meet_v2.SpacesServiceClient", - "shortName": "SpacesServiceClient" + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient", + "shortName": "ConferenceRecordsServiceClient" }, - "fullName": "google.apps.meet_v2.SpacesServiceClient.create_space", + "fullName": "google.apps.meet_v2.ConferenceRecordsServiceClient.list_transcripts", "method": { - "fullName": "google.apps.meet.v2.SpacesService.CreateSpace", + "fullName": "google.apps.meet.v2.ConferenceRecordsService.ListTranscripts", "service": { - "fullName": "google.apps.meet.v2.SpacesService", - "shortName": "SpacesService" + "fullName": "google.apps.meet.v2.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" }, - "shortName": "CreateSpace" + "shortName": "ListTranscripts" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.CreateSpaceRequest" + "type": "google.apps.meet_v2.types.ListTranscriptsRequest" }, { - "name": "space", - "type": "google.apps.meet_v2.types.Space" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -2054,22 +2215,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.types.Space", - "shortName": "create_space" + "resultType": "google.apps.meet_v2.services.conference_records_service.pagers.ListTranscriptsPager", + "shortName": "list_transcripts" }, - "description": "Sample for CreateSpace", - "file": "meet_v2_generated_spaces_service_create_space_sync.py", + "description": "Sample for ListTranscripts", + "file": "meet_v2_generated_conference_records_service_list_transcripts_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_SpacesService_CreateSpace_sync", + "regionTag": "meet_v2_generated_ConferenceRecordsService_ListTranscripts_sync", "segments": [ { - "end": 50, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2079,22 +2240,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_spaces_service_create_space_sync.py" + "title": "meet_v2_generated_conference_records_service_list_transcripts_sync.py" }, { "canonical": true, @@ -2104,23 +2265,19 @@ "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", "shortName": "SpacesServiceAsyncClient" }, - "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.end_active_conference", + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.batch_update_members", "method": { - "fullName": "google.apps.meet.v2.SpacesService.EndActiveConference", + "fullName": "google.apps.meet.v2.SpacesService.BatchUpdateMembers", "service": { "fullName": "google.apps.meet.v2.SpacesService", "shortName": "SpacesService" }, - "shortName": "EndActiveConference" + "shortName": "BatchUpdateMembers" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.EndActiveConferenceRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.apps.meet_v2.types.BatchUpdateMembersRequest" }, { "name": "retry", @@ -2135,21 +2292,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "end_active_conference" + "resultType": "google.apps.meet_v2.types.BatchUpdateMembersResponse", + "shortName": "batch_update_members" }, - "description": "Sample for EndActiveConference", - "file": "meet_v2_generated_spaces_service_end_active_conference_async.py", + "description": "Sample for BatchUpdateMembers", + "file": "meet_v2_generated_spaces_service_batch_update_members_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_SpacesService_EndActiveConference_async", + "regionTag": "meet_v2_generated_SpacesService_BatchUpdateMembers_async", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2164,15 +2322,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_spaces_service_end_active_conference_async.py" + "title": "meet_v2_generated_spaces_service_batch_update_members_async.py" }, { "canonical": true, @@ -2181,23 +2341,19 @@ "fullName": "google.apps.meet_v2.SpacesServiceClient", "shortName": "SpacesServiceClient" }, - "fullName": "google.apps.meet_v2.SpacesServiceClient.end_active_conference", + "fullName": "google.apps.meet_v2.SpacesServiceClient.batch_update_members", "method": { - "fullName": "google.apps.meet.v2.SpacesService.EndActiveConference", + "fullName": "google.apps.meet.v2.SpacesService.BatchUpdateMembers", "service": { "fullName": "google.apps.meet.v2.SpacesService", "shortName": "SpacesService" }, - "shortName": "EndActiveConference" + "shortName": "BatchUpdateMembers" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.EndActiveConferenceRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.apps.meet_v2.types.BatchUpdateMembersRequest" }, { "name": "retry", @@ -2212,21 +2368,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "end_active_conference" + "resultType": "google.apps.meet_v2.types.BatchUpdateMembersResponse", + "shortName": "batch_update_members" }, - "description": "Sample for EndActiveConference", - "file": "meet_v2_generated_spaces_service_end_active_conference_sync.py", + "description": "Sample for BatchUpdateMembers", + "file": "meet_v2_generated_spaces_service_batch_update_members_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_SpacesService_EndActiveConference_sync", + "regionTag": "meet_v2_generated_SpacesService_BatchUpdateMembers_sync", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2241,15 +2398,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_spaces_service_end_active_conference_sync.py" + "title": "meet_v2_generated_spaces_service_batch_update_members_sync.py" }, { "canonical": true, @@ -2259,24 +2418,28 @@ "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", "shortName": "SpacesServiceAsyncClient" }, - "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.get_space", + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.create_member", "method": { - "fullName": "google.apps.meet.v2.SpacesService.GetSpace", + "fullName": "google.apps.meet.v2.SpacesService.CreateMember", "service": { "fullName": "google.apps.meet.v2.SpacesService", "shortName": "SpacesService" }, - "shortName": "GetSpace" + "shortName": "CreateMember" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.GetSpaceRequest" + "type": "google.apps.meet_v2.types.CreateMemberRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "member", + "type": "google.apps.meet_v2.types.Member" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -2290,14 +2453,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.types.Space", - "shortName": "get_space" + "resultType": "google.apps.meet_v2.types.Member", + "shortName": "create_member" }, - "description": "Sample for GetSpace", - "file": "meet_v2_generated_spaces_service_get_space_async.py", + "description": "Sample for CreateMember", + "file": "meet_v2_generated_spaces_service_create_member_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_SpacesService_GetSpace_async", + "regionTag": "meet_v2_generated_SpacesService_CreateMember_async", "segments": [ { "end": 51, @@ -2330,7 +2493,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_spaces_service_get_space_async.py" + "title": "meet_v2_generated_spaces_service_create_member_async.py" }, { "canonical": true, @@ -2339,24 +2502,28 @@ "fullName": "google.apps.meet_v2.SpacesServiceClient", "shortName": "SpacesServiceClient" }, - "fullName": "google.apps.meet_v2.SpacesServiceClient.get_space", + "fullName": "google.apps.meet_v2.SpacesServiceClient.create_member", "method": { - "fullName": "google.apps.meet.v2.SpacesService.GetSpace", + "fullName": "google.apps.meet.v2.SpacesService.CreateMember", "service": { "fullName": "google.apps.meet.v2.SpacesService", "shortName": "SpacesService" }, - "shortName": "GetSpace" + "shortName": "CreateMember" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2.types.GetSpaceRequest" + "type": "google.apps.meet_v2.types.CreateMemberRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "member", + "type": "google.apps.meet_v2.types.Member" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -2370,14 +2537,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2.types.Space", - "shortName": "get_space" + "resultType": "google.apps.meet_v2.types.Member", + "shortName": "create_member" }, - "description": "Sample for GetSpace", - "file": "meet_v2_generated_spaces_service_get_space_sync.py", + "description": "Sample for CreateMember", + "file": "meet_v2_generated_spaces_service_create_member_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2_generated_SpacesService_GetSpace_sync", + "regionTag": "meet_v2_generated_SpacesService_CreateMember_sync", "segments": [ { "end": 51, @@ -2410,7 +2577,1130 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2_generated_spaces_service_get_space_sync.py" + "title": "meet_v2_generated_spaces_service_create_member_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.create_space", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.CreateSpace", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "CreateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.CreateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.meet_v2.types.Space" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Space", + "shortName": "create_space" + }, + "description": "Sample for CreateSpace", + "file": "meet_v2_generated_spaces_service_create_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_CreateSpace_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_create_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceClient.create_space", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.CreateSpace", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "CreateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.CreateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.meet_v2.types.Space" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Space", + "shortName": "create_space" + }, + "description": "Sample for CreateSpace", + "file": "meet_v2_generated_spaces_service_create_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_CreateSpace_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_create_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.delete_member", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.DeleteMember", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "DeleteMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.DeleteMemberRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_member" + }, + "description": "Sample for DeleteMember", + "file": "meet_v2_generated_spaces_service_delete_member_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_DeleteMember_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_delete_member_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceClient.delete_member", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.DeleteMember", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "DeleteMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.DeleteMemberRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_member" + }, + "description": "Sample for DeleteMember", + "file": "meet_v2_generated_spaces_service_delete_member_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_DeleteMember_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_delete_member_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.end_active_conference", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.EndActiveConference", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "EndActiveConference" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.EndActiveConferenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "end_active_conference" + }, + "description": "Sample for EndActiveConference", + "file": "meet_v2_generated_spaces_service_end_active_conference_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_EndActiveConference_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_end_active_conference_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceClient.end_active_conference", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.EndActiveConference", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "EndActiveConference" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.EndActiveConferenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "end_active_conference" + }, + "description": "Sample for EndActiveConference", + "file": "meet_v2_generated_spaces_service_end_active_conference_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_EndActiveConference_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_end_active_conference_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.get_member", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.GetMember", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "GetMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.GetMemberRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Member", + "shortName": "get_member" + }, + "description": "Sample for GetMember", + "file": "meet_v2_generated_spaces_service_get_member_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_GetMember_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_get_member_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceClient.get_member", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.GetMember", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "GetMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.GetMemberRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Member", + "shortName": "get_member" + }, + "description": "Sample for GetMember", + "file": "meet_v2_generated_spaces_service_get_member_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_GetMember_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_get_member_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.get_space", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.GetSpace", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "GetSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.GetSpaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Space", + "shortName": "get_space" + }, + "description": "Sample for GetSpace", + "file": "meet_v2_generated_spaces_service_get_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_GetSpace_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_get_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceClient.get_space", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.GetSpace", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "GetSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.GetSpaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Space", + "shortName": "get_space" + }, + "description": "Sample for GetSpace", + "file": "meet_v2_generated_spaces_service_get_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_GetSpace_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_get_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.list_members", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.ListMembers", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "ListMembers" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.ListMembersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.services.spaces_service.pagers.ListMembersAsyncPager", + "shortName": "list_members" + }, + "description": "Sample for ListMembers", + "file": "meet_v2_generated_spaces_service_list_members_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_ListMembers_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_list_members_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceClient.list_members", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.ListMembers", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "ListMembers" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.ListMembersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.services.spaces_service.pagers.ListMembersPager", + "shortName": "list_members" + }, + "description": "Sample for ListMembers", + "file": "meet_v2_generated_spaces_service_list_members_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_ListMembers_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_list_members_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceAsyncClient.update_member", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.UpdateMember", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "UpdateMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.UpdateMemberRequest" + }, + { + "name": "member", + "type": "google.apps.meet_v2.types.Member" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Member", + "shortName": "update_member" + }, + "description": "Sample for UpdateMember", + "file": "meet_v2_generated_spaces_service_update_member_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_UpdateMember_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_update_member_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2.SpacesServiceClient.update_member", + "method": { + "fullName": "google.apps.meet.v2.SpacesService.UpdateMember", + "service": { + "fullName": "google.apps.meet.v2.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "UpdateMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2.types.UpdateMemberRequest" + }, + { + "name": "member", + "type": "google.apps.meet_v2.types.Member" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2.types.Member", + "shortName": "update_member" + }, + "description": "Sample for UpdateMember", + "file": "meet_v2_generated_spaces_service_update_member_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2_generated_SpacesService_UpdateMember_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2_generated_spaces_service_update_member_sync.py" }, { "canonical": true, diff --git a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json index cb97ce7d6cb4..53c2d4d42bae 100644 --- a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json +++ b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-apps-meet", - "version": "0.5.0" + "version": "0.5.1" }, "snippets": [ { @@ -655,6 +655,167 @@ ], "title": "meet_v2beta_generated_conference_records_service_get_recording_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient", + "shortName": "ConferenceRecordsServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient.get_smart_note", + "method": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.GetSmartNote", + "service": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "GetSmartNote" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.GetSmartNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.types.SmartNote", + "shortName": "get_smart_note" + }, + "description": "Sample for GetSmartNote", + "file": "meet_v2beta_generated_conference_records_service_get_smart_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_GetSmartNote_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_conference_records_service_get_smart_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient", + "shortName": "ConferenceRecordsServiceClient" + }, + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient.get_smart_note", + "method": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.GetSmartNote", + "service": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "GetSmartNote" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.GetSmartNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.types.SmartNote", + "shortName": "get_smart_note" + }, + "description": "Sample for GetSmartNote", + "file": "meet_v2beta_generated_conference_records_service_get_smart_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_GetSmartNote_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_conference_records_service_get_smart_note_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1574,11 +1735,333 @@ "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListRecordingsPager", "shortName": "list_recordings" }, - "description": "Sample for ListRecordings", - "file": "meet_v2beta_generated_conference_records_service_list_recordings_sync.py", + "description": "Sample for ListRecordings", + "file": "meet_v2beta_generated_conference_records_service_list_recordings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListRecordings_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_conference_records_service_list_recordings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient", + "shortName": "ConferenceRecordsServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient.list_smart_notes", + "method": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListSmartNotes", + "service": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "ListSmartNotes" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.ListSmartNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListSmartNotesAsyncPager", + "shortName": "list_smart_notes" + }, + "description": "Sample for ListSmartNotes", + "file": "meet_v2beta_generated_conference_records_service_list_smart_notes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListSmartNotes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_conference_records_service_list_smart_notes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient", + "shortName": "ConferenceRecordsServiceClient" + }, + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient.list_smart_notes", + "method": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListSmartNotes", + "service": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "ListSmartNotes" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.ListSmartNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListSmartNotesPager", + "shortName": "list_smart_notes" + }, + "description": "Sample for ListSmartNotes", + "file": "meet_v2beta_generated_conference_records_service_list_smart_notes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListSmartNotes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_conference_records_service_list_smart_notes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient", + "shortName": "ConferenceRecordsServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient.list_transcript_entries", + "method": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscriptEntries", + "service": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "ListTranscriptEntries" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.ListTranscriptEntriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptEntriesAsyncPager", + "shortName": "list_transcript_entries" + }, + "description": "Sample for ListTranscriptEntries", + "file": "meet_v2beta_generated_conference_records_service_list_transcript_entries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscriptEntries_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_conference_records_service_list_transcript_entries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient", + "shortName": "ConferenceRecordsServiceClient" + }, + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient.list_transcript_entries", + "method": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscriptEntries", + "service": { + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", + "shortName": "ConferenceRecordsService" + }, + "shortName": "ListTranscriptEntries" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.ListTranscriptEntriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptEntriesPager", + "shortName": "list_transcript_entries" + }, + "description": "Sample for ListTranscriptEntries", + "file": "meet_v2beta_generated_conference_records_service_list_transcript_entries_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListRecordings_sync", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscriptEntries_sync", "segments": [ { "end": 52, @@ -1611,7 +2094,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2beta_generated_conference_records_service_list_recordings_sync.py" + "title": "meet_v2beta_generated_conference_records_service_list_transcript_entries_sync.py" }, { "canonical": true, @@ -1621,19 +2104,19 @@ "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient", "shortName": "ConferenceRecordsServiceAsyncClient" }, - "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient.list_transcript_entries", + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient.list_transcripts", "method": { - "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscriptEntries", + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscripts", "service": { "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", "shortName": "ConferenceRecordsService" }, - "shortName": "ListTranscriptEntries" + "shortName": "ListTranscripts" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2beta.types.ListTranscriptEntriesRequest" + "type": "google.apps.meet_v2beta.types.ListTranscriptsRequest" }, { "name": "parent", @@ -1652,14 +2135,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptEntriesAsyncPager", - "shortName": "list_transcript_entries" + "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptsAsyncPager", + "shortName": "list_transcripts" }, - "description": "Sample for ListTranscriptEntries", - "file": "meet_v2beta_generated_conference_records_service_list_transcript_entries_async.py", + "description": "Sample for ListTranscripts", + "file": "meet_v2beta_generated_conference_records_service_list_transcripts_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscriptEntries_async", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscripts_async", "segments": [ { "end": 52, @@ -1692,7 +2175,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2beta_generated_conference_records_service_list_transcript_entries_async.py" + "title": "meet_v2beta_generated_conference_records_service_list_transcripts_async.py" }, { "canonical": true, @@ -1701,19 +2184,19 @@ "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient", "shortName": "ConferenceRecordsServiceClient" }, - "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient.list_transcript_entries", + "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient.list_transcripts", "method": { - "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscriptEntries", + "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscripts", "service": { "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", "shortName": "ConferenceRecordsService" }, - "shortName": "ListTranscriptEntries" + "shortName": "ListTranscripts" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2beta.types.ListTranscriptEntriesRequest" + "type": "google.apps.meet_v2beta.types.ListTranscriptsRequest" }, { "name": "parent", @@ -1732,14 +2215,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptEntriesPager", - "shortName": "list_transcript_entries" + "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptsPager", + "shortName": "list_transcripts" }, - "description": "Sample for ListTranscriptEntries", - "file": "meet_v2beta_generated_conference_records_service_list_transcript_entries_sync.py", + "description": "Sample for ListTranscripts", + "file": "meet_v2beta_generated_conference_records_service_list_transcripts_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscriptEntries_sync", + "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscripts_sync", "segments": [ { "end": 52, @@ -1772,33 +2255,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2beta_generated_conference_records_service_list_transcript_entries_sync.py" + "title": "meet_v2beta_generated_conference_records_service_list_transcripts_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient", - "shortName": "ConferenceRecordsServiceAsyncClient" + "fullName": "google.apps.meet_v2beta.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" }, - "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceAsyncClient.list_transcripts", + "fullName": "google.apps.meet_v2beta.SpacesServiceAsyncClient.batch_update_members", "method": { - "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscripts", + "fullName": "google.apps.meet.v2beta.SpacesService.BatchUpdateMembers", "service": { - "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", - "shortName": "ConferenceRecordsService" + "fullName": "google.apps.meet.v2beta.SpacesService", + "shortName": "SpacesService" }, - "shortName": "ListTranscripts" + "shortName": "BatchUpdateMembers" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2beta.types.ListTranscriptsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.apps.meet_v2beta.types.BatchUpdateMembersRequest" }, { "name": "retry", @@ -1813,22 +2292,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptsAsyncPager", - "shortName": "list_transcripts" + "resultType": "google.apps.meet_v2beta.types.BatchUpdateMembersResponse", + "shortName": "batch_update_members" }, - "description": "Sample for ListTranscripts", - "file": "meet_v2beta_generated_conference_records_service_list_transcripts_async.py", + "description": "Sample for BatchUpdateMembers", + "file": "meet_v2beta_generated_spaces_service_batch_update_members_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscripts_async", + "regionTag": "meet_v2beta_generated_SpacesService_BatchUpdateMembers_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1848,37 +2327,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2beta_generated_conference_records_service_list_transcripts_async.py" + "title": "meet_v2beta_generated_spaces_service_batch_update_members_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient", - "shortName": "ConferenceRecordsServiceClient" + "fullName": "google.apps.meet_v2beta.SpacesServiceClient", + "shortName": "SpacesServiceClient" }, - "fullName": "google.apps.meet_v2beta.ConferenceRecordsServiceClient.list_transcripts", + "fullName": "google.apps.meet_v2beta.SpacesServiceClient.batch_update_members", "method": { - "fullName": "google.apps.meet.v2beta.ConferenceRecordsService.ListTranscripts", + "fullName": "google.apps.meet.v2beta.SpacesService.BatchUpdateMembers", "service": { - "fullName": "google.apps.meet.v2beta.ConferenceRecordsService", - "shortName": "ConferenceRecordsService" + "fullName": "google.apps.meet.v2beta.SpacesService", + "shortName": "SpacesService" }, - "shortName": "ListTranscripts" + "shortName": "BatchUpdateMembers" }, "parameters": [ { "name": "request", - "type": "google.apps.meet_v2beta.types.ListTranscriptsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.apps.meet_v2beta.types.BatchUpdateMembersRequest" }, { "name": "retry", @@ -1893,22 +2368,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.meet_v2beta.services.conference_records_service.pagers.ListTranscriptsPager", - "shortName": "list_transcripts" + "resultType": "google.apps.meet_v2beta.types.BatchUpdateMembersResponse", + "shortName": "batch_update_members" }, - "description": "Sample for ListTranscripts", - "file": "meet_v2beta_generated_conference_records_service_list_transcripts_sync.py", + "description": "Sample for BatchUpdateMembers", + "file": "meet_v2beta_generated_spaces_service_batch_update_members_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "meet_v2beta_generated_ConferenceRecordsService_ListTranscripts_sync", + "regionTag": "meet_v2beta_generated_SpacesService_BatchUpdateMembers_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1928,12 +2403,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "meet_v2beta_generated_conference_records_service_list_transcripts_sync.py" + "title": "meet_v2beta_generated_spaces_service_batch_update_members_sync.py" }, { "canonical": true, @@ -3219,6 +3694,175 @@ ], "title": "meet_v2beta_generated_spaces_service_list_members_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.meet_v2beta.SpacesServiceAsyncClient", + "shortName": "SpacesServiceAsyncClient" + }, + "fullName": "google.apps.meet_v2beta.SpacesServiceAsyncClient.update_member", + "method": { + "fullName": "google.apps.meet.v2beta.SpacesService.UpdateMember", + "service": { + "fullName": "google.apps.meet.v2beta.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "UpdateMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.UpdateMemberRequest" + }, + { + "name": "member", + "type": "google.apps.meet_v2beta.types.Member" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.types.Member", + "shortName": "update_member" + }, + "description": "Sample for UpdateMember", + "file": "meet_v2beta_generated_spaces_service_update_member_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_SpacesService_UpdateMember_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_spaces_service_update_member_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.meet_v2beta.SpacesServiceClient", + "shortName": "SpacesServiceClient" + }, + "fullName": "google.apps.meet_v2beta.SpacesServiceClient.update_member", + "method": { + "fullName": "google.apps.meet.v2beta.SpacesService.UpdateMember", + "service": { + "fullName": "google.apps.meet.v2beta.SpacesService", + "shortName": "SpacesService" + }, + "shortName": "UpdateMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.meet_v2beta.types.UpdateMemberRequest" + }, + { + "name": "member", + "type": "google.apps.meet_v2beta.types.Member" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.meet_v2beta.types.Member", + "shortName": "update_member" + }, + "description": "Sample for UpdateMember", + "file": "meet_v2beta_generated_spaces_service_update_member_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "meet_v2beta_generated_SpacesService_UpdateMember_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "meet_v2beta_generated_spaces_service_update_member_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py index 0d34ea47ecaa..e75652331503 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py @@ -6234,6 +6234,853 @@ async def test_list_transcript_entries_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + service.GetSmartNoteRequest(), + {}, + ], +) +def test_get_smart_note(request_type, transport: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.SmartNote( + name="name_value", + state=resource.SmartNote.State.STARTED, + ) + response = client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetSmartNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.SmartNote) + assert response.name == "name_value" + assert response.state == resource.SmartNote.State.STARTED + + +def test_get_smart_note_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetSmartNoteRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_smart_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSmartNoteRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_smart_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_smart_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_smart_note] = mock_rpc + request = {} + client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_smart_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_smart_note_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_smart_note + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_smart_note + ] = mock_rpc + + request = {} + await client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_smart_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.GetSmartNoteRequest(), + {}, + ], +) +async def test_get_smart_note_async(request_type, transport: str = "grpc_asyncio"): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.SmartNote( + name="name_value", + state=resource.SmartNote.State.STARTED, + ) + ) + response = await client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetSmartNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.SmartNote) + assert response.name == "name_value" + assert response.state == resource.SmartNote.State.STARTED + + +def test_get_smart_note_field_headers(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSmartNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value = resource.SmartNote() + client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_smart_note_field_headers_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSmartNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.SmartNote()) + await client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_smart_note_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.SmartNote() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_smart_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_smart_note_flattened_error(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_smart_note( + service.GetSmartNoteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_smart_note_flattened_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.SmartNote() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.SmartNote()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_smart_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_smart_note_flattened_error_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_smart_note( + service.GetSmartNoteRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListSmartNotesRequest(), + {}, + ], +) +def test_list_smart_notes(request_type, transport: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSmartNotesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListSmartNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSmartNotesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_smart_notes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListSmartNotesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_smart_notes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_smart_notes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_smart_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_smart_notes] = ( + mock_rpc + ) + request = {} + client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_smart_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_smart_notes_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_smart_notes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_smart_notes + ] = mock_rpc + + request = {} + await client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_smart_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.ListSmartNotesRequest(), + {}, + ], +) +async def test_list_smart_notes_async(request_type, transport: str = "grpc_asyncio"): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSmartNotesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListSmartNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSmartNotesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_smart_notes_field_headers(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSmartNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value = service.ListSmartNotesResponse() + client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_smart_notes_field_headers_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSmartNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSmartNotesResponse() + ) + await client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_smart_notes_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSmartNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_smart_notes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_smart_notes_flattened_error(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_smart_notes( + service.ListSmartNotesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_smart_notes_flattened_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSmartNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSmartNotesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_smart_notes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_smart_notes_flattened_error_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_smart_notes( + service.ListSmartNotesRequest(), + parent="parent_value", + ) + + +def test_list_smart_notes_pager(transport_name: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_smart_notes(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.SmartNote) for i in results) + + +def test_list_smart_notes_pages(transport_name: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + pages = list(client.list_smart_notes(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_smart_notes_async_pager(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_smart_notes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_smart_notes( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resource.SmartNote) for i in responses) + + +@pytest.mark.asyncio +async def test_list_smart_notes_async_pages(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_smart_notes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_smart_notes(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_get_conference_record_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6248,35 +7095,309 @@ def test_get_conference_record_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_conference_record - in client._transport._wrapped_methods - ) + assert ( + client._transport.get_conference_record + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_conference_record] = ( + mock_rpc + ) + + request = {} + client.get_conference_record(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conference_record(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_conference_record_rest_required_fields( + request_type=service.GetConferenceRecordRequest, +): + transport_class = transports.ConferenceRecordsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetConferenceRecord, + "_BaseGetConferenceRecord__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.ConferenceRecord() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.ConferenceRecord.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_conference_record(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_conference_record_rest_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.ConferenceRecord() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "conferenceRecords/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.ConferenceRecord.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_conference_record(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=conferenceRecords/*}" % client.transport._host, args[1] + ) + + +def test_get_conference_record_rest_flattened_error(transport: str = "rest"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_conference_record( + service.GetConferenceRecordRequest(), + name="name_value", + ) + + +def test_list_conference_records_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_conference_records + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_conference_records + ] = mock_rpc + + request = {} + client.list_conference_records(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conference_records(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_conference_records_rest_pager(transport: str = "rest"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListConferenceRecordsResponse( + conference_records=[ + resource.ConferenceRecord(), + resource.ConferenceRecord(), + resource.ConferenceRecord(), + ], + next_page_token="abc", + ), + service.ListConferenceRecordsResponse( + conference_records=[], + next_page_token="def", + ), + service.ListConferenceRecordsResponse( + conference_records=[ + resource.ConferenceRecord(), + ], + next_page_token="ghi", + ), + service.ListConferenceRecordsResponse( + conference_records=[ + resource.ConferenceRecord(), + resource.ConferenceRecord(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListConferenceRecordsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_conference_records(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.ConferenceRecord) for i in results) + + pages = list(client.list_conference_records(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_participant_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_participant in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_conference_record] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_participant] = mock_rpc request = {} - client.get_conference_record(request) + client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_conference_record(request) + client.get_participant(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_conference_record_rest_required_fields( - request_type=service.GetConferenceRecordRequest, +def test_get_participant_rest_required_fields( + request_type=service.GetParticipantRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -6291,8 +7412,8 @@ def test_get_conference_record_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetConferenceRecord, - "_BaseGetConferenceRecord__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetParticipant, + "_BaseGetParticipant__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6315,7 +7436,7 @@ def test_get_conference_record_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.ConferenceRecord() + return_value = resource.Participant() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6336,21 +7457,21 @@ def test_get_conference_record_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ConferenceRecord.pb(return_value) + return_value = resource.Participant.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_conference_record(request) + response = client.get_participant(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_conference_record_rest_flattened(): +def test_get_participant_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6359,10 +7480,10 @@ def test_get_conference_record_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ConferenceRecord() + return_value = resource.Participant() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1"} + sample_request = {"name": "conferenceRecords/sample1/participants/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -6374,24 +7495,25 @@ def test_get_conference_record_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ConferenceRecord.pb(return_value) + return_value = resource.Participant.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_conference_record(**mock_args) + client.get_participant(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=conferenceRecords/*}" % client.transport._host, args[1] + "%s/v2/{name=conferenceRecords/*/participants/*}" % client.transport._host, + args[1], ) -def test_get_conference_record_rest_flattened_error(transport: str = "rest"): +def test_get_participant_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6400,13 +7522,13 @@ def test_get_conference_record_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_conference_record( - service.GetConferenceRecordRequest(), + client.get_participant( + service.GetParticipantRequest(), name="name_value", ) -def test_list_conference_records_rest_use_cached_wrapped_rpc(): +def test_list_participants_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6420,34 +7542,172 @@ def test_list_conference_records_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_conference_records - in client._transport._wrapped_methods - ) + assert client._transport.list_participants in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_conference_records - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_participants] = ( + mock_rpc + ) request = {} - client.list_conference_records(request) + client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_conference_records(request) + client.list_participants(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_conference_records_rest_pager(transport: str = "rest"): +def test_list_participants_rest_required_fields( + request_type=service.ListParticipantsRequest, +): + transport_class = transports.ConferenceRecordsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListParticipants, + "_BaseListParticipants__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListParticipantsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListParticipantsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_participants(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_participants_rest_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListParticipantsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "conferenceRecords/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListParticipantsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_participants(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=conferenceRecords/*}/participants" % client.transport._host, + args[1], + ) + + +def test_list_participants_rest_flattened_error(transport: str = "rest"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_participants( + service.ListParticipantsRequest(), + parent="parent_value", + ) + + +def test_list_participants_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6459,28 +7719,28 @@ def test_list_conference_records_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListConferenceRecordsResponse( - conference_records=[ - resource.ConferenceRecord(), - resource.ConferenceRecord(), - resource.ConferenceRecord(), + service.ListParticipantsResponse( + participants=[ + resource.Participant(), + resource.Participant(), + resource.Participant(), ], next_page_token="abc", ), - service.ListConferenceRecordsResponse( - conference_records=[], + service.ListParticipantsResponse( + participants=[], next_page_token="def", ), - service.ListConferenceRecordsResponse( - conference_records=[ - resource.ConferenceRecord(), + service.ListParticipantsResponse( + participants=[ + resource.Participant(), ], next_page_token="ghi", ), - service.ListConferenceRecordsResponse( - conference_records=[ - resource.ConferenceRecord(), - resource.ConferenceRecord(), + service.ListParticipantsResponse( + participants=[ + resource.Participant(), + resource.Participant(), ], ), ) @@ -6488,32 +7748,30 @@ def test_list_conference_records_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - service.ListConferenceRecordsResponse.to_json(x) for x in response - ) + response = tuple(service.ListParticipantsResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {} + sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_conference_records(request=sample_request) + pager = client.list_participants(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.ConferenceRecord) for i in results) + assert all(isinstance(i, resource.Participant) for i in results) - pages = list(client.list_conference_records(request=sample_request).pages) + pages = list(client.list_participants(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_participant_rest_use_cached_wrapped_rpc(): +def test_get_participant_session_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6527,30 +7785,35 @@ def test_get_participant_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_participant in client._transport._wrapped_methods + assert ( + client._transport.get_participant_session + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_participant] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_participant_session + ] = mock_rpc request = {} - client.get_participant(request) + client.get_participant_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_participant(request) + client.get_participant_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_participant_rest_required_fields( - request_type=service.GetParticipantRequest, +def test_get_participant_session_rest_required_fields( + request_type=service.GetParticipantSessionRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -6565,8 +7828,8 @@ def test_get_participant_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetParticipant, - "_BaseGetParticipant__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetParticipantSession, + "_BaseGetParticipantSession__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6589,7 +7852,7 @@ def test_get_participant_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Participant() + return_value = resource.ParticipantSession() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6610,21 +7873,21 @@ def test_get_participant_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Participant.pb(return_value) + return_value = resource.ParticipantSession.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant(request) + response = client.get_participant_session(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_participant_rest_flattened(): +def test_get_participant_session_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6633,10 +7896,12 @@ def test_get_participant_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Participant() + return_value = resource.ParticipantSession() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1/participants/sample2"} + sample_request = { + "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -6648,25 +7913,26 @@ def test_get_participant_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Participant.pb(return_value) + return_value = resource.ParticipantSession.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant(**mock_args) + client.get_participant_session(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=conferenceRecords/*/participants/*}" % client.transport._host, + "%s/v2/{name=conferenceRecords/*/participants/*/participantSessions/*}" + % client.transport._host, args[1], ) -def test_get_participant_rest_flattened_error(transport: str = "rest"): +def test_get_participant_session_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6675,13 +7941,13 @@ def test_get_participant_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_participant( - service.GetParticipantRequest(), + client.get_participant_session( + service.GetParticipantSessionRequest(), name="name_value", ) -def test_list_participants_rest_use_cached_wrapped_rpc(): +def test_list_participant_sessions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6695,32 +7961,35 @@ def test_list_participants_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_participants in client._transport._wrapped_methods + assert ( + client._transport.list_participant_sessions + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_participants] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_participant_sessions + ] = mock_rpc request = {} - client.list_participants(request) + client.list_participant_sessions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_participants(request) + client.list_participant_sessions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_participants_rest_required_fields( - request_type=service.ListParticipantsRequest, +def test_list_participant_sessions_rest_required_fields( + request_type=service.ListParticipantSessionsRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -6735,8 +8004,8 @@ def test_list_participants_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListParticipants, - "_BaseListParticipants__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListParticipantSessions, + "_BaseListParticipantSessions__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6768,7 +8037,7 @@ def test_list_participants_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListParticipantsResponse() + return_value = service.ListParticipantSessionsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6789,21 +8058,21 @@ def test_list_participants_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantsResponse.pb(return_value) + return_value = service.ListParticipantSessionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participants(request) + response = client.list_participant_sessions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_participants_rest_flattened(): +def test_list_participant_sessions_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6812,10 +8081,10 @@ def test_list_participants_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantsResponse() + return_value = service.ListParticipantSessionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -6827,25 +8096,26 @@ def test_list_participants_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantsResponse.pb(return_value) + return_value = service.ListParticipantSessionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participants(**mock_args) + client.list_participant_sessions(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=conferenceRecords/*}/participants" % client.transport._host, + "%s/v2/{parent=conferenceRecords/*/participants/*}/participantSessions" + % client.transport._host, args[1], ) -def test_list_participants_rest_flattened_error(transport: str = "rest"): +def test_list_participant_sessions_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6854,13 +8124,13 @@ def test_list_participants_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_participants( - service.ListParticipantsRequest(), + client.list_participant_sessions( + service.ListParticipantSessionsRequest(), parent="parent_value", ) -def test_list_participants_rest_pager(transport: str = "rest"): +def test_list_participant_sessions_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6872,28 +8142,28 @@ def test_list_participants_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListParticipantsResponse( - participants=[ - resource.Participant(), - resource.Participant(), - resource.Participant(), + service.ListParticipantSessionsResponse( + participant_sessions=[ + resource.ParticipantSession(), + resource.ParticipantSession(), + resource.ParticipantSession(), ], next_page_token="abc", ), - service.ListParticipantsResponse( - participants=[], + service.ListParticipantSessionsResponse( + participant_sessions=[], next_page_token="def", ), - service.ListParticipantsResponse( - participants=[ - resource.Participant(), + service.ListParticipantSessionsResponse( + participant_sessions=[ + resource.ParticipantSession(), ], next_page_token="ghi", ), - service.ListParticipantsResponse( - participants=[ - resource.Participant(), - resource.Participant(), + service.ListParticipantSessionsResponse( + participant_sessions=[ + resource.ParticipantSession(), + resource.ParticipantSession(), ], ), ) @@ -6901,30 +8171,32 @@ def test_list_participants_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListParticipantsResponse.to_json(x) for x in response) + response = tuple( + service.ListParticipantSessionsResponse.to_json(x) for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} - pager = client.list_participants(request=sample_request) + pager = client.list_participant_sessions(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.Participant) for i in results) + assert all(isinstance(i, resource.ParticipantSession) for i in results) - pages = list(client.list_participants(request=sample_request).pages) + pages = list(client.list_participant_sessions(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_participant_session_rest_use_cached_wrapped_rpc(): +def test_get_recording_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6938,36 +8210,29 @@ def test_get_participant_session_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_participant_session - in client._transport._wrapped_methods - ) + assert client._transport.get_recording in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_participant_session - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_recording] = mock_rpc request = {} - client.get_participant_session(request) + client.get_recording(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_participant_session(request) + client.get_recording(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_participant_session_rest_required_fields( - request_type=service.GetParticipantSessionRequest, -): +def test_get_recording_rest_required_fields(request_type=service.GetRecordingRequest): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -6981,8 +8246,8 @@ def test_get_participant_session_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetParticipantSession, - "_BaseGetParticipantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetRecording, + "_BaseGetRecording__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7005,7 +8270,7 @@ def test_get_participant_session_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.ParticipantSession() + return_value = resource.Recording() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7026,21 +8291,21 @@ def test_get_participant_session_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ParticipantSession.pb(return_value) + return_value = resource.Recording.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant_session(request) + response = client.get_recording(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_participant_session_rest_flattened(): +def test_get_recording_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7049,12 +8314,10 @@ def test_get_participant_session_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ParticipantSession() + return_value = resource.Recording() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" - } + sample_request = {"name": "conferenceRecords/sample1/recordings/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -7066,26 +8329,25 @@ def test_get_participant_session_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ParticipantSession.pb(return_value) + return_value = resource.Recording.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant_session(**mock_args) + client.get_recording(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=conferenceRecords/*/participants/*/participantSessions/*}" - % client.transport._host, + "%s/v2/{name=conferenceRecords/*/recordings/*}" % client.transport._host, args[1], ) -def test_get_participant_session_rest_flattened_error(transport: str = "rest"): +def test_get_recording_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7094,13 +8356,13 @@ def test_get_participant_session_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_participant_session( - service.GetParticipantSessionRequest(), + client.get_recording( + service.GetRecordingRequest(), name="name_value", ) -def test_list_participant_sessions_rest_use_cached_wrapped_rpc(): +def test_list_recordings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7114,35 +8376,30 @@ def test_list_participant_sessions_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_participant_sessions - in client._transport._wrapped_methods - ) + assert client._transport.list_recordings in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_participant_sessions - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_recordings] = mock_rpc request = {} - client.list_participant_sessions(request) + client.list_recordings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_participant_sessions(request) + client.list_recordings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_participant_sessions_rest_required_fields( - request_type=service.ListParticipantSessionsRequest, +def test_list_recordings_rest_required_fields( + request_type=service.ListRecordingsRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -7157,8 +8414,8 @@ def test_list_participant_sessions_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListParticipantSessions, - "_BaseListParticipantSessions__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListRecordings, + "_BaseListRecordings__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7173,7 +8430,6 @@ def test_list_participant_sessions_rest_required_fields( # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", "pageSize", "pageToken", ) @@ -7190,7 +8446,7 @@ def test_list_participant_sessions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListParticipantSessionsResponse() + return_value = service.ListRecordingsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7211,21 +8467,21 @@ def test_list_participant_sessions_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantSessionsResponse.pb(return_value) + return_value = service.ListRecordingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participant_sessions(request) + response = client.list_recordings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_participant_sessions_rest_flattened(): +def test_list_recordings_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7234,10 +8490,10 @@ def test_list_participant_sessions_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantSessionsResponse() + return_value = service.ListRecordingsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -7249,26 +8505,25 @@ def test_list_participant_sessions_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantSessionsResponse.pb(return_value) + return_value = service.ListRecordingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participant_sessions(**mock_args) + client.list_recordings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=conferenceRecords/*/participants/*}/participantSessions" - % client.transport._host, + "%s/v2/{parent=conferenceRecords/*}/recordings" % client.transport._host, args[1], ) -def test_list_participant_sessions_rest_flattened_error(transport: str = "rest"): +def test_list_recordings_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7277,13 +8532,13 @@ def test_list_participant_sessions_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_participant_sessions( - service.ListParticipantSessionsRequest(), + client.list_recordings( + service.ListRecordingsRequest(), parent="parent_value", ) -def test_list_participant_sessions_rest_pager(transport: str = "rest"): +def test_list_recordings_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7295,28 +8550,28 @@ def test_list_participant_sessions_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListParticipantSessionsResponse( - participant_sessions=[ - resource.ParticipantSession(), - resource.ParticipantSession(), - resource.ParticipantSession(), + service.ListRecordingsResponse( + recordings=[ + resource.Recording(), + resource.Recording(), + resource.Recording(), ], next_page_token="abc", ), - service.ListParticipantSessionsResponse( - participant_sessions=[], + service.ListRecordingsResponse( + recordings=[], next_page_token="def", ), - service.ListParticipantSessionsResponse( - participant_sessions=[ - resource.ParticipantSession(), + service.ListRecordingsResponse( + recordings=[ + resource.Recording(), ], next_page_token="ghi", ), - service.ListParticipantSessionsResponse( - participant_sessions=[ - resource.ParticipantSession(), - resource.ParticipantSession(), + service.ListRecordingsResponse( + recordings=[ + resource.Recording(), + resource.Recording(), ], ), ) @@ -7324,32 +8579,30 @@ def test_list_participant_sessions_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - service.ListParticipantSessionsResponse.to_json(x) for x in response - ) + response = tuple(service.ListRecordingsResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_participant_sessions(request=sample_request) + pager = client.list_recordings(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.ParticipantSession) for i in results) + assert all(isinstance(i, resource.Recording) for i in results) - pages = list(client.list_participant_sessions(request=sample_request).pages) + pages = list(client.list_recordings(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_recording_rest_use_cached_wrapped_rpc(): +def test_get_transcript_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7363,29 +8616,29 @@ def test_get_recording_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_recording in client._transport._wrapped_methods + assert client._transport.get_transcript in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_recording] = mock_rpc + client._transport._wrapped_methods[client._transport.get_transcript] = mock_rpc request = {} - client.get_recording(request) + client.get_transcript(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_recording(request) + client.get_transcript(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_recording_rest_required_fields(request_type=service.GetRecordingRequest): +def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptRequest): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -7399,8 +8652,8 @@ def test_get_recording_rest_required_fields(request_type=service.GetRecordingReq # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetRecording, - "_BaseGetRecording__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetTranscript, + "_BaseGetTranscript__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7423,7 +8676,7 @@ def test_get_recording_rest_required_fields(request_type=service.GetRecordingReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Recording() + return_value = resource.Transcript() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7444,21 +8697,21 @@ def test_get_recording_rest_required_fields(request_type=service.GetRecordingReq response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Recording.pb(return_value) + return_value = resource.Transcript.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_recording(request) + response = client.get_transcript(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_recording_rest_flattened(): +def test_get_transcript_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7467,10 +8720,10 @@ def test_get_recording_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Recording() + return_value = resource.Transcript() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1/recordings/sample2"} + sample_request = {"name": "conferenceRecords/sample1/transcripts/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -7482,25 +8735,25 @@ def test_get_recording_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Recording.pb(return_value) + return_value = resource.Transcript.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_recording(**mock_args) + client.get_transcript(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=conferenceRecords/*/recordings/*}" % client.transport._host, + "%s/v2/{name=conferenceRecords/*/transcripts/*}" % client.transport._host, args[1], ) -def test_get_recording_rest_flattened_error(transport: str = "rest"): +def test_get_transcript_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7509,13 +8762,13 @@ def test_get_recording_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_recording( - service.GetRecordingRequest(), + client.get_transcript( + service.GetTranscriptRequest(), name="name_value", ) -def test_list_recordings_rest_use_cached_wrapped_rpc(): +def test_list_transcripts_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7529,30 +8782,32 @@ def test_list_recordings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_recordings in client._transport._wrapped_methods + assert client._transport.list_transcripts in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_recordings] = mock_rpc + client._transport._wrapped_methods[client._transport.list_transcripts] = ( + mock_rpc + ) request = {} - client.list_recordings(request) + client.list_transcripts(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_recordings(request) + client.list_transcripts(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_recordings_rest_required_fields( - request_type=service.ListRecordingsRequest, +def test_list_transcripts_rest_required_fields( + request_type=service.ListTranscriptsRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -7567,8 +8822,8 @@ def test_list_recordings_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListRecordings, - "_BaseListRecordings__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListTranscripts, + "_BaseListTranscripts__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7599,7 +8854,7 @@ def test_list_recordings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListRecordingsResponse() + return_value = service.ListTranscriptsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7620,21 +8875,21 @@ def test_list_recordings_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRecordingsResponse.pb(return_value) + return_value = service.ListTranscriptsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_recordings(request) + response = client.list_transcripts(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_recordings_rest_flattened(): +def test_list_transcripts_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7643,7 +8898,7 @@ def test_list_recordings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListRecordingsResponse() + return_value = service.ListTranscriptsResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "conferenceRecords/sample1"} @@ -7658,25 +8913,25 @@ def test_list_recordings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRecordingsResponse.pb(return_value) + return_value = service.ListTranscriptsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_recordings(**mock_args) + client.list_transcripts(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=conferenceRecords/*}/recordings" % client.transport._host, + "%s/v2/{parent=conferenceRecords/*}/transcripts" % client.transport._host, args[1], ) -def test_list_recordings_rest_flattened_error(transport: str = "rest"): +def test_list_transcripts_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7685,13 +8940,13 @@ def test_list_recordings_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_recordings( - service.ListRecordingsRequest(), + client.list_transcripts( + service.ListTranscriptsRequest(), parent="parent_value", ) -def test_list_recordings_rest_pager(transport: str = "rest"): +def test_list_transcripts_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7703,28 +8958,28 @@ def test_list_recordings_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListRecordingsResponse( - recordings=[ - resource.Recording(), - resource.Recording(), - resource.Recording(), + service.ListTranscriptsResponse( + transcripts=[ + resource.Transcript(), + resource.Transcript(), + resource.Transcript(), ], next_page_token="abc", ), - service.ListRecordingsResponse( - recordings=[], + service.ListTranscriptsResponse( + transcripts=[], next_page_token="def", ), - service.ListRecordingsResponse( - recordings=[ - resource.Recording(), + service.ListTranscriptsResponse( + transcripts=[ + resource.Transcript(), ], next_page_token="ghi", ), - service.ListRecordingsResponse( - recordings=[ - resource.Recording(), - resource.Recording(), + service.ListTranscriptsResponse( + transcripts=[ + resource.Transcript(), + resource.Transcript(), ], ), ) @@ -7732,7 +8987,7 @@ def test_list_recordings_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListRecordingsResponse.to_json(x) for x in response) + response = tuple(service.ListTranscriptsResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") @@ -7741,21 +8996,21 @@ def test_list_recordings_rest_pager(transport: str = "rest"): sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_recordings(request=sample_request) + pager = client.list_transcripts(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.Recording) for i in results) + assert all(isinstance(i, resource.Transcript) for i in results) - pages = list(client.list_recordings(request=sample_request).pages) + pages = list(client.list_transcripts(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_transcript_rest_use_cached_wrapped_rpc(): +def test_get_transcript_entry_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7769,29 +9024,35 @@ def test_get_transcript_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_transcript in client._transport._wrapped_methods + assert ( + client._transport.get_transcript_entry in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_transcript] = mock_rpc + client._transport._wrapped_methods[client._transport.get_transcript_entry] = ( + mock_rpc + ) request = {} - client.get_transcript(request) + client.get_transcript_entry(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_transcript(request) + client.get_transcript_entry(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptRequest): +def test_get_transcript_entry_rest_required_fields( + request_type=service.GetTranscriptEntryRequest, +): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -7805,8 +9066,8 @@ def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptR # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetTranscript, - "_BaseGetTranscript__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetTranscriptEntry, + "_BaseGetTranscriptEntry__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7829,7 +9090,7 @@ def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Transcript() + return_value = resource.TranscriptEntry() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7850,21 +9111,21 @@ def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptR response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Transcript.pb(return_value) + return_value = resource.TranscriptEntry.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript(request) + response = client.get_transcript_entry(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_transcript_rest_flattened(): +def test_get_transcript_entry_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7873,10 +9134,12 @@ def test_get_transcript_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Transcript() + return_value = resource.TranscriptEntry() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1/transcripts/sample2"} + sample_request = { + "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -7888,25 +9151,26 @@ def test_get_transcript_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Transcript.pb(return_value) + return_value = resource.TranscriptEntry.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript(**mock_args) + client.get_transcript_entry(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=conferenceRecords/*/transcripts/*}" % client.transport._host, + "%s/v2/{name=conferenceRecords/*/transcripts/*/entries/*}" + % client.transport._host, args[1], ) -def test_get_transcript_rest_flattened_error(transport: str = "rest"): +def test_get_transcript_entry_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7915,13 +9179,13 @@ def test_get_transcript_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_transcript( - service.GetTranscriptRequest(), + client.get_transcript_entry( + service.GetTranscriptEntryRequest(), name="name_value", ) -def test_list_transcripts_rest_use_cached_wrapped_rpc(): +def test_list_transcript_entries_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7935,32 +9199,35 @@ def test_list_transcripts_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_transcripts in client._transport._wrapped_methods + assert ( + client._transport.list_transcript_entries + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_transcripts] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_transcript_entries + ] = mock_rpc request = {} - client.list_transcripts(request) + client.list_transcript_entries(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_transcripts(request) + client.list_transcript_entries(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_transcripts_rest_required_fields( - request_type=service.ListTranscriptsRequest, +def test_list_transcript_entries_rest_required_fields( + request_type=service.ListTranscriptEntriesRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -7975,8 +9242,8 @@ def test_list_transcripts_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListTranscripts, - "_BaseListTranscripts__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListTranscriptEntries, + "_BaseListTranscriptEntries__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -8007,7 +9274,7 @@ def test_list_transcripts_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptsResponse() + return_value = service.ListTranscriptEntriesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8028,21 +9295,21 @@ def test_list_transcripts_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptsResponse.pb(return_value) + return_value = service.ListTranscriptEntriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcripts(request) + response = client.list_transcript_entries(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_transcripts_rest_flattened(): +def test_list_transcript_entries_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8051,10 +9318,10 @@ def test_list_transcripts_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptsResponse() + return_value = service.ListTranscriptEntriesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -8066,25 +9333,26 @@ def test_list_transcripts_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptsResponse.pb(return_value) + return_value = service.ListTranscriptEntriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcripts(**mock_args) + client.list_transcript_entries(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=conferenceRecords/*}/transcripts" % client.transport._host, + "%s/v2/{parent=conferenceRecords/*/transcripts/*}/entries" + % client.transport._host, args[1], ) -def test_list_transcripts_rest_flattened_error(transport: str = "rest"): +def test_list_transcript_entries_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8093,13 +9361,13 @@ def test_list_transcripts_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_transcripts( - service.ListTranscriptsRequest(), + client.list_transcript_entries( + service.ListTranscriptEntriesRequest(), parent="parent_value", ) -def test_list_transcripts_rest_pager(transport: str = "rest"): +def test_list_transcript_entries_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8111,28 +9379,28 @@ def test_list_transcripts_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListTranscriptsResponse( - transcripts=[ - resource.Transcript(), - resource.Transcript(), - resource.Transcript(), + service.ListTranscriptEntriesResponse( + transcript_entries=[ + resource.TranscriptEntry(), + resource.TranscriptEntry(), + resource.TranscriptEntry(), ], next_page_token="abc", ), - service.ListTranscriptsResponse( - transcripts=[], + service.ListTranscriptEntriesResponse( + transcript_entries=[], next_page_token="def", ), - service.ListTranscriptsResponse( - transcripts=[ - resource.Transcript(), + service.ListTranscriptEntriesResponse( + transcript_entries=[ + resource.TranscriptEntry(), ], next_page_token="ghi", ), - service.ListTranscriptsResponse( - transcripts=[ - resource.Transcript(), - resource.Transcript(), + service.ListTranscriptEntriesResponse( + transcript_entries=[ + resource.TranscriptEntry(), + resource.TranscriptEntry(), ], ), ) @@ -8140,30 +9408,32 @@ def test_list_transcripts_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListTranscriptsResponse.to_json(x) for x in response) + response = tuple( + service.ListTranscriptEntriesResponse.to_json(x) for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} - pager = client.list_transcripts(request=sample_request) + pager = client.list_transcript_entries(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.Transcript) for i in results) + assert all(isinstance(i, resource.TranscriptEntry) for i in results) - pages = list(client.list_transcripts(request=sample_request).pages) + pages = list(client.list_transcript_entries(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_transcript_entry_rest_use_cached_wrapped_rpc(): +def test_get_smart_note_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8177,35 +9447,29 @@ def test_get_transcript_entry_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_transcript_entry in client._transport._wrapped_methods - ) + assert client._transport.get_smart_note in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_transcript_entry] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_smart_note] = mock_rpc request = {} - client.get_transcript_entry(request) + client.get_smart_note(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_transcript_entry(request) + client.get_smart_note(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_transcript_entry_rest_required_fields( - request_type=service.GetTranscriptEntryRequest, -): +def test_get_smart_note_rest_required_fields(request_type=service.GetSmartNoteRequest): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -8219,8 +9483,8 @@ def test_get_transcript_entry_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetTranscriptEntry, - "_BaseGetTranscriptEntry__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetSmartNote, + "_BaseGetSmartNote__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -8243,7 +9507,7 @@ def test_get_transcript_entry_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.TranscriptEntry() + return_value = resource.SmartNote() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8264,21 +9528,21 @@ def test_get_transcript_entry_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.TranscriptEntry.pb(return_value) + return_value = resource.SmartNote.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript_entry(request) + response = client.get_smart_note(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_transcript_entry_rest_flattened(): +def test_get_smart_note_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8287,12 +9551,10 @@ def test_get_transcript_entry_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.TranscriptEntry() + return_value = resource.SmartNote() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" - } + sample_request = {"name": "conferenceRecords/sample1/smartNotes/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -8304,26 +9566,25 @@ def test_get_transcript_entry_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.TranscriptEntry.pb(return_value) + return_value = resource.SmartNote.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript_entry(**mock_args) + client.get_smart_note(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=conferenceRecords/*/transcripts/*/entries/*}" - % client.transport._host, + "%s/v2/{name=conferenceRecords/*/smartNotes/*}" % client.transport._host, args[1], ) -def test_get_transcript_entry_rest_flattened_error(transport: str = "rest"): +def test_get_smart_note_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8332,13 +9593,13 @@ def test_get_transcript_entry_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_transcript_entry( - service.GetTranscriptEntryRequest(), + client.get_smart_note( + service.GetSmartNoteRequest(), name="name_value", ) -def test_list_transcript_entries_rest_use_cached_wrapped_rpc(): +def test_list_smart_notes_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8352,35 +9613,32 @@ def test_list_transcript_entries_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_transcript_entries - in client._transport._wrapped_methods - ) + assert client._transport.list_smart_notes in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_transcript_entries - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_smart_notes] = ( + mock_rpc + ) request = {} - client.list_transcript_entries(request) + client.list_smart_notes(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_transcript_entries(request) + client.list_smart_notes(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_transcript_entries_rest_required_fields( - request_type=service.ListTranscriptEntriesRequest, +def test_list_smart_notes_rest_required_fields( + request_type=service.ListSmartNotesRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -8395,8 +9653,8 @@ def test_list_transcript_entries_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListTranscriptEntries, - "_BaseListTranscriptEntries__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListSmartNotes, + "_BaseListSmartNotes__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -8427,7 +9685,7 @@ def test_list_transcript_entries_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptEntriesResponse() + return_value = service.ListSmartNotesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8448,21 +9706,21 @@ def test_list_transcript_entries_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptEntriesResponse.pb(return_value) + return_value = service.ListSmartNotesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcript_entries(request) + response = client.list_smart_notes(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_transcript_entries_rest_flattened(): +def test_list_smart_notes_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8471,10 +9729,10 @@ def test_list_transcript_entries_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptEntriesResponse() + return_value = service.ListSmartNotesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -8486,26 +9744,25 @@ def test_list_transcript_entries_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptEntriesResponse.pb(return_value) + return_value = service.ListSmartNotesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcript_entries(**mock_args) + client.list_smart_notes(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=conferenceRecords/*/transcripts/*}/entries" - % client.transport._host, + "%s/v2/{parent=conferenceRecords/*}/smartNotes" % client.transport._host, args[1], ) -def test_list_transcript_entries_rest_flattened_error(transport: str = "rest"): +def test_list_smart_notes_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8514,13 +9771,13 @@ def test_list_transcript_entries_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_transcript_entries( - service.ListTranscriptEntriesRequest(), + client.list_smart_notes( + service.ListSmartNotesRequest(), parent="parent_value", ) -def test_list_transcript_entries_rest_pager(transport: str = "rest"): +def test_list_smart_notes_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8532,28 +9789,28 @@ def test_list_transcript_entries_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListTranscriptEntriesResponse( - transcript_entries=[ - resource.TranscriptEntry(), - resource.TranscriptEntry(), - resource.TranscriptEntry(), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), ], next_page_token="abc", ), - service.ListTranscriptEntriesResponse( - transcript_entries=[], + service.ListSmartNotesResponse( + smart_notes=[], next_page_token="def", ), - service.ListTranscriptEntriesResponse( - transcript_entries=[ - resource.TranscriptEntry(), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), ], next_page_token="ghi", ), - service.ListTranscriptEntriesResponse( - transcript_entries=[ - resource.TranscriptEntry(), - resource.TranscriptEntry(), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), ], ), ) @@ -8561,27 +9818,25 @@ def test_list_transcript_entries_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - service.ListTranscriptEntriesResponse.to_json(x) for x in response - ) + response = tuple(service.ListSmartNotesResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_transcript_entries(request=sample_request) + pager = client.list_smart_notes(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.TranscriptEntry) for i in results) + assert all(isinstance(i, resource.SmartNote) for i in results) - pages = list(client.list_transcript_entries(request=sample_request).pages) + pages = list(client.list_smart_notes(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -8946,6 +10201,46 @@ def test_list_transcript_entries_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_smart_note_empty_call_grpc(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value = resource.SmartNote() + client.get_smart_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSmartNoteRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_smart_notes_empty_call_grpc(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value = service.ListSmartNotesResponse() + client.list_smart_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = ConferenceRecordsServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -9058,256 +10353,580 @@ async def test_list_participants_empty_call_grpc_asyncio(): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListParticipantsResponse( + service.ListParticipantsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.list_participants(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListParticipantsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_participant_session_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_participant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.ParticipantSession( + name="name_value", + ) + ) + await client.get_participant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetParticipantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_participant_sessions_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_participant_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListParticipantSessionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_participant_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListParticipantSessionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_recording_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_recording), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Recording( + name="name_value", + state=resource.Recording.State.STARTED, + ) + ) + await client.get_recording(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetRecordingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_recordings_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_recordings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListRecordingsResponse( next_page_token="next_page_token_value", - total_size=1086, ) ) - await client.list_participants(request=None) + await client.list_recordings(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListParticipantsRequest() + request_msg = service.ListRecordingsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_participant_session_empty_call_grpc_asyncio(): +async def test_get_transcript_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_participant_session), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_transcript), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.ParticipantSession( + resource.Transcript( name="name_value", + state=resource.Transcript.State.STARTED, ) ) - await client.get_participant_session(request=None) + await client.get_transcript(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetParticipantSessionRequest() + request_msg = service.GetTranscriptRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_participant_sessions_empty_call_grpc_asyncio(): +async def test_list_transcripts_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_participant_sessions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_transcripts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListParticipantSessionsResponse( + service.ListTranscriptsResponse( next_page_token="next_page_token_value", ) ) - await client.list_participant_sessions(request=None) + await client.list_transcripts(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListParticipantSessionsRequest() + request_msg = service.ListTranscriptsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_recording_empty_call_grpc_asyncio(): +async def test_get_transcript_entry_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_recording), "__call__") as call: + with mock.patch.object( + type(client.transport.get_transcript_entry), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.Recording( + resource.TranscriptEntry( name="name_value", - state=resource.Recording.State.STARTED, + participant="participant_value", + text="text_value", + language_code="language_code_value", ) ) - await client.get_recording(request=None) + await client.get_transcript_entry(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetRecordingRequest() + request_msg = service.GetTranscriptEntryRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_recordings_empty_call_grpc_asyncio(): +async def test_list_transcript_entries_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_recordings), "__call__") as call: + with mock.patch.object( + type(client.transport.list_transcript_entries), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListRecordingsResponse( + service.ListTranscriptEntriesResponse( next_page_token="next_page_token_value", ) ) - await client.list_recordings(request=None) + await client.list_transcript_entries(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListRecordingsRequest() + request_msg = service.ListTranscriptEntriesRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_transcript_empty_call_grpc_asyncio(): +async def test_get_smart_note_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_transcript), "__call__") as call: + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.Transcript( + resource.SmartNote( name="name_value", - state=resource.Transcript.State.STARTED, + state=resource.SmartNote.State.STARTED, ) ) - await client.get_transcript(request=None) + await client.get_smart_note(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetTranscriptRequest() + request_msg = service.GetSmartNoteRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_transcripts_empty_call_grpc_asyncio(): +async def test_list_smart_notes_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_transcripts), "__call__") as call: + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListTranscriptsResponse( + service.ListSmartNotesResponse( next_page_token="next_page_token_value", ) ) - await client.list_transcripts(request=None) + await client.list_smart_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ConferenceRecordsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_conference_record_rest_bad_request( + request_type=service.GetConferenceRecordRequest, +): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "conferenceRecords/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_conference_record(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetConferenceRecordRequest, + dict, + ], +) +def test_get_conference_record_rest_call_success(request_type): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "conferenceRecords/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.ConferenceRecord( + name="name_value", + space="space_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.ConferenceRecord.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_conference_record(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.ConferenceRecord) + assert response.name == "name_value" + assert response.space == "space_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conference_record_rest_interceptors(null_interceptor): + transport = transports.ConferenceRecordsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ConferenceRecordsServiceRestInterceptor(), + ) + client = ConferenceRecordsServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_conference_record", + ) as post, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_conference_record_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "pre_get_conference_record", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetConferenceRecordRequest.pb( + service.GetConferenceRecordRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.ConferenceRecord.to_json(resource.ConferenceRecord()) + req.return_value.content = return_value + + request = service.GetConferenceRecordRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.ConferenceRecord() + post_with_metadata.return_value = resource.ConferenceRecord(), metadata + + client.get_conference_record( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_conference_records_rest_bad_request( + request_type=service.ListConferenceRecordsRequest, +): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_conference_records(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListConferenceRecordsRequest, + dict, + ], +) +def test_list_conference_records_rest_call_success(request_type): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListTranscriptsRequest() - assert args[0] == request_msg + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListConferenceRecordsResponse( + next_page_token="next_page_token_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_transcript_entry_empty_call_grpc_asyncio(): - client = ConferenceRecordsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_transcript_entry), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.TranscriptEntry( - name="name_value", - participant="participant_value", - text="text_value", - language_code="language_code_value", - ) - ) - await client.get_transcript_entry(request=None) + # Convert return value to protobuf type + return_value = service.ListConferenceRecordsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_conference_records(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetTranscriptEntryRequest() - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConferenceRecordsPager) + assert response.next_page_token == "next_page_token_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_transcript_entries_empty_call_grpc_asyncio(): - client = ConferenceRecordsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conference_records_rest_interceptors(null_interceptor): + transport = transports.ConferenceRecordsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ConferenceRecordsServiceRestInterceptor(), ) + client = ConferenceRecordsServiceClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_transcript_entries), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListTranscriptEntriesResponse( - next_page_token="next_page_token_value", - ) + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_conference_records", + ) as post, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_conference_records_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "pre_list_conference_records", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListConferenceRecordsRequest.pb( + service.ListConferenceRecordsRequest() ) - await client.list_transcript_entries(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListTranscriptEntriesRequest() - assert args[0] == request_msg + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListConferenceRecordsResponse.to_json( + service.ListConferenceRecordsResponse() + ) + req.return_value.content = return_value + + request = service.ListConferenceRecordsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListConferenceRecordsResponse() + post_with_metadata.return_value = ( + service.ListConferenceRecordsResponse(), + metadata, + ) + client.list_conference_records( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = ConferenceRecordsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_conference_record_rest_bad_request( - request_type=service.GetConferenceRecordRequest, -): +def test_get_participant_rest_bad_request(request_type=service.GetParticipantRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1"} + request_init = {"name": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9323,31 +10942,30 @@ def test_get_conference_record_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_conference_record(request) + client.get_participant(request) @pytest.mark.parametrize( "request_type", [ - service.GetConferenceRecordRequest, + service.GetParticipantRequest, dict, ], ) -def test_get_conference_record_rest_call_success(request_type): +def test_get_participant_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1"} + request_init = {"name": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ConferenceRecord( + return_value = resource.Participant( name="name_value", - space="space_value", ) # Wrap the value into a proper Response obj @@ -9355,21 +10973,20 @@ def test_get_conference_record_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ConferenceRecord.pb(return_value) + return_value = resource.Participant.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_conference_record(request) + response = client.get_participant(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.ConferenceRecord) + assert isinstance(response, resource.Participant) assert response.name == "name_value" - assert response.space == "space_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conference_record_rest_interceptors(null_interceptor): +def test_get_participant_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9382,24 +10999,20 @@ def test_get_conference_record_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_get_conference_record", + transports.ConferenceRecordsServiceRestInterceptor, "post_get_participant" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_conference_record_with_metadata", + "post_get_participant_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_get_conference_record", + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_participant" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetConferenceRecordRequest.pb( - service.GetConferenceRecordRequest() - ) + pb_message = service.GetParticipantRequest.pb(service.GetParticipantRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9410,19 +11023,19 @@ def test_get_conference_record_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.ConferenceRecord.to_json(resource.ConferenceRecord()) + return_value = resource.Participant.to_json(resource.Participant()) req.return_value.content = return_value - request = service.GetConferenceRecordRequest() + request = service.GetParticipantRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.ConferenceRecord() - post_with_metadata.return_value = resource.ConferenceRecord(), metadata + post.return_value = resource.Participant() + post_with_metadata.return_value = resource.Participant(), metadata - client.get_conference_record( + client.get_participant( request, metadata=[ ("key", "val"), @@ -9435,14 +11048,14 @@ def test_get_conference_record_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_conference_records_rest_bad_request( - request_type=service.ListConferenceRecordsRequest, +def test_list_participants_rest_bad_request( + request_type=service.ListParticipantsRequest, ): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9458,30 +11071,31 @@ def test_list_conference_records_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_conference_records(request) + client.list_participants(request) @pytest.mark.parametrize( "request_type", [ - service.ListConferenceRecordsRequest, + service.ListParticipantsRequest, dict, ], ) -def test_list_conference_records_rest_call_success(request_type): +def test_list_participants_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListConferenceRecordsResponse( + return_value = service.ListParticipantsResponse( next_page_token="next_page_token_value", + total_size=1086, ) # Wrap the value into a proper Response obj @@ -9489,20 +11103,21 @@ def test_list_conference_records_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListConferenceRecordsResponse.pb(return_value) + return_value = service.ListParticipantsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_conference_records(request) + response = client.list_participants(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConferenceRecordsPager) + assert isinstance(response, pagers.ListParticipantsPager) assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conference_records_rest_interceptors(null_interceptor): +def test_list_participants_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9515,23 +11130,21 @@ def test_list_conference_records_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_list_conference_records", + transports.ConferenceRecordsServiceRestInterceptor, "post_list_participants" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_conference_records_with_metadata", + "post_list_participants_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_list_conference_records", + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_participants" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListConferenceRecordsRequest.pb( - service.ListConferenceRecordsRequest() + pb_message = service.ListParticipantsRequest.pb( + service.ListParticipantsRequest() ) transcode.return_value = { "method": "post", @@ -9543,24 +11156,21 @@ def test_list_conference_records_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListConferenceRecordsResponse.to_json( - service.ListConferenceRecordsResponse() + return_value = service.ListParticipantsResponse.to_json( + service.ListParticipantsResponse() ) req.return_value.content = return_value - request = service.ListConferenceRecordsRequest() + request = service.ListParticipantsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListConferenceRecordsResponse() - post_with_metadata.return_value = ( - service.ListConferenceRecordsResponse(), - metadata, - ) + post.return_value = service.ListParticipantsResponse() + post_with_metadata.return_value = service.ListParticipantsResponse(), metadata - client.list_conference_records( + client.list_participants( request, metadata=[ ("key", "val"), @@ -9573,12 +11183,16 @@ def test_list_conference_records_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_participant_rest_bad_request(request_type=service.GetParticipantRequest): +def test_get_participant_session_rest_bad_request( + request_type=service.GetParticipantSessionRequest, +): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/participants/sample2"} + request_init = { + "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9594,29 +11208,31 @@ def test_get_participant_rest_bad_request(request_type=service.GetParticipantReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant(request) + client.get_participant_session(request) @pytest.mark.parametrize( "request_type", [ - service.GetParticipantRequest, + service.GetParticipantSessionRequest, dict, ], ) -def test_get_participant_rest_call_success(request_type): +def test_get_participant_session_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/participants/sample2"} + request_init = { + "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Participant( + return_value = resource.ParticipantSession( name="name_value", ) @@ -9625,20 +11241,20 @@ def test_get_participant_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Participant.pb(return_value) + return_value = resource.ParticipantSession.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant(request) + response = client.get_participant_session(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Participant) + assert isinstance(response, resource.ParticipantSession) assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_participant_rest_interceptors(null_interceptor): +def test_get_participant_session_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9651,20 +11267,24 @@ def test_get_participant_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_get_participant" + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_participant_session", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_participant_with_metadata", + "post_get_participant_session_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_get_participant" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_get_participant_session", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetParticipantRequest.pb(service.GetParticipantRequest()) + pb_message = service.GetParticipantSessionRequest.pb( + service.GetParticipantSessionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9675,19 +11295,21 @@ def test_get_participant_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Participant.to_json(resource.Participant()) + return_value = resource.ParticipantSession.to_json( + resource.ParticipantSession() + ) req.return_value.content = return_value - request = service.GetParticipantRequest() + request = service.GetParticipantSessionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Participant() - post_with_metadata.return_value = resource.Participant(), metadata + post.return_value = resource.ParticipantSession() + post_with_metadata.return_value = resource.ParticipantSession(), metadata - client.get_participant( + client.get_participant_session( request, metadata=[ ("key", "val"), @@ -9700,14 +11322,14 @@ def test_get_participant_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_participants_rest_bad_request( - request_type=service.ListParticipantsRequest, +def test_list_participant_sessions_rest_bad_request( + request_type=service.ListParticipantSessionsRequest, ): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9723,31 +11345,30 @@ def test_list_participants_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participants(request) + client.list_participant_sessions(request) @pytest.mark.parametrize( "request_type", [ - service.ListParticipantsRequest, + service.ListParticipantSessionsRequest, dict, ], ) -def test_list_participants_rest_call_success(request_type): +def test_list_participant_sessions_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantsResponse( + return_value = service.ListParticipantSessionsResponse( next_page_token="next_page_token_value", - total_size=1086, ) # Wrap the value into a proper Response obj @@ -9755,21 +11376,20 @@ def test_list_participants_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantsResponse.pb(return_value) + return_value = service.ListParticipantSessionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participants(request) + response = client.list_participant_sessions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) + assert isinstance(response, pagers.ListParticipantSessionsPager) assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_participants_rest_interceptors(null_interceptor): +def test_list_participant_sessions_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9782,21 +11402,23 @@ def test_list_participants_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_list_participants" + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_participant_sessions", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_participants_with_metadata", + "post_list_participant_sessions_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_list_participants" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_list_participant_sessions", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListParticipantsRequest.pb( - service.ListParticipantsRequest() + pb_message = service.ListParticipantSessionsRequest.pb( + service.ListParticipantSessionsRequest() ) transcode.return_value = { "method": "post", @@ -9808,21 +11430,24 @@ def test_list_participants_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListParticipantsResponse.to_json( - service.ListParticipantsResponse() + return_value = service.ListParticipantSessionsResponse.to_json( + service.ListParticipantSessionsResponse() ) req.return_value.content = return_value - request = service.ListParticipantsRequest() + request = service.ListParticipantSessionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListParticipantsResponse() - post_with_metadata.return_value = service.ListParticipantsResponse(), metadata + post.return_value = service.ListParticipantSessionsResponse() + post_with_metadata.return_value = ( + service.ListParticipantSessionsResponse(), + metadata, + ) - client.list_participants( + client.list_participant_sessions( request, metadata=[ ("key", "val"), @@ -9835,16 +11460,12 @@ def test_list_participants_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_participant_session_rest_bad_request( - request_type=service.GetParticipantSessionRequest, -): +def test_get_recording_rest_bad_request(request_type=service.GetRecordingRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" - } + request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9860,32 +11481,31 @@ def test_get_participant_session_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant_session(request) + client.get_recording(request) @pytest.mark.parametrize( "request_type", [ - service.GetParticipantSessionRequest, + service.GetRecordingRequest, dict, ], ) -def test_get_participant_session_rest_call_success(request_type): +def test_get_recording_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" - } + request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ParticipantSession( + return_value = resource.Recording( name="name_value", + state=resource.Recording.State.STARTED, ) # Wrap the value into a proper Response obj @@ -9893,20 +11513,21 @@ def test_get_participant_session_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ParticipantSession.pb(return_value) + return_value = resource.Recording.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant_session(request) + response = client.get_recording(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.ParticipantSession) + assert isinstance(response, resource.Recording) assert response.name == "name_value" + assert response.state == resource.Recording.State.STARTED @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_participant_session_rest_interceptors(null_interceptor): +def test_get_recording_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9919,24 +11540,20 @@ def test_get_participant_session_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_get_participant_session", + transports.ConferenceRecordsServiceRestInterceptor, "post_get_recording" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_participant_session_with_metadata", + "post_get_recording_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_get_participant_session", + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_recording" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetParticipantSessionRequest.pb( - service.GetParticipantSessionRequest() - ) + pb_message = service.GetRecordingRequest.pb(service.GetRecordingRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9947,21 +11564,19 @@ def test_get_participant_session_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.ParticipantSession.to_json( - resource.ParticipantSession() - ) + return_value = resource.Recording.to_json(resource.Recording()) req.return_value.content = return_value - request = service.GetParticipantSessionRequest() + request = service.GetRecordingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.ParticipantSession() - post_with_metadata.return_value = resource.ParticipantSession(), metadata + post.return_value = resource.Recording() + post_with_metadata.return_value = resource.Recording(), metadata - client.get_participant_session( + client.get_recording( request, metadata=[ ("key", "val"), @@ -9974,14 +11589,12 @@ def test_get_participant_session_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_participant_sessions_rest_bad_request( - request_type=service.ListParticipantSessionsRequest, -): +def test_list_recordings_rest_bad_request(request_type=service.ListRecordingsRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9997,29 +11610,29 @@ def test_list_participant_sessions_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participant_sessions(request) + client.list_recordings(request) @pytest.mark.parametrize( "request_type", [ - service.ListParticipantSessionsRequest, + service.ListRecordingsRequest, dict, ], ) -def test_list_participant_sessions_rest_call_success(request_type): +def test_list_recordings_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantSessionsResponse( + return_value = service.ListRecordingsResponse( next_page_token="next_page_token_value", ) @@ -10028,20 +11641,20 @@ def test_list_participant_sessions_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantSessionsResponse.pb(return_value) + return_value = service.ListRecordingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participant_sessions(request) + response = client.list_recordings(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantSessionsPager) + assert isinstance(response, pagers.ListRecordingsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_participant_sessions_rest_interceptors(null_interceptor): +def test_list_recordings_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10054,24 +11667,20 @@ def test_list_participant_sessions_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_list_participant_sessions", + transports.ConferenceRecordsServiceRestInterceptor, "post_list_recordings" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_participant_sessions_with_metadata", + "post_list_recordings_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_list_participant_sessions", + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_recordings" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListParticipantSessionsRequest.pb( - service.ListParticipantSessionsRequest() - ) + pb_message = service.ListRecordingsRequest.pb(service.ListRecordingsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10082,24 +11691,21 @@ def test_list_participant_sessions_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListParticipantSessionsResponse.to_json( - service.ListParticipantSessionsResponse() + return_value = service.ListRecordingsResponse.to_json( + service.ListRecordingsResponse() ) req.return_value.content = return_value - request = service.ListParticipantSessionsRequest() + request = service.ListRecordingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListParticipantSessionsResponse() - post_with_metadata.return_value = ( - service.ListParticipantSessionsResponse(), - metadata, - ) + post.return_value = service.ListRecordingsResponse() + post_with_metadata.return_value = service.ListRecordingsResponse(), metadata - client.list_participant_sessions( + client.list_recordings( request, metadata=[ ("key", "val"), @@ -10112,12 +11718,12 @@ def test_list_participant_sessions_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_recording_rest_bad_request(request_type=service.GetRecordingRequest): +def test_get_transcript_rest_bad_request(request_type=service.GetTranscriptRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} + request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10133,31 +11739,31 @@ def test_get_recording_rest_bad_request(request_type=service.GetRecordingRequest response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_recording(request) + client.get_transcript(request) @pytest.mark.parametrize( "request_type", [ - service.GetRecordingRequest, + service.GetTranscriptRequest, dict, ], ) -def test_get_recording_rest_call_success(request_type): +def test_get_transcript_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} + request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Recording( + return_value = resource.Transcript( name="name_value", - state=resource.Recording.State.STARTED, + state=resource.Transcript.State.STARTED, ) # Wrap the value into a proper Response obj @@ -10165,21 +11771,21 @@ def test_get_recording_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Recording.pb(return_value) + return_value = resource.Transcript.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_recording(request) + response = client.get_transcript(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Recording) + assert isinstance(response, resource.Transcript) assert response.name == "name_value" - assert response.state == resource.Recording.State.STARTED + assert response.state == resource.Transcript.State.STARTED @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_recording_rest_interceptors(null_interceptor): +def test_get_transcript_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10192,20 +11798,20 @@ def test_get_recording_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_get_recording" + transports.ConferenceRecordsServiceRestInterceptor, "post_get_transcript" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_recording_with_metadata", + "post_get_transcript_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_get_recording" + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_transcript" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetRecordingRequest.pb(service.GetRecordingRequest()) + pb_message = service.GetTranscriptRequest.pb(service.GetTranscriptRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10216,19 +11822,19 @@ def test_get_recording_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Recording.to_json(resource.Recording()) + return_value = resource.Transcript.to_json(resource.Transcript()) req.return_value.content = return_value - request = service.GetRecordingRequest() + request = service.GetTranscriptRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Recording() - post_with_metadata.return_value = resource.Recording(), metadata + post.return_value = resource.Transcript() + post_with_metadata.return_value = resource.Transcript(), metadata - client.get_recording( + client.get_transcript( request, metadata=[ ("key", "val"), @@ -10241,7 +11847,7 @@ def test_get_recording_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_recordings_rest_bad_request(request_type=service.ListRecordingsRequest): +def test_list_transcripts_rest_bad_request(request_type=service.ListTranscriptsRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10262,17 +11868,17 @@ def test_list_recordings_rest_bad_request(request_type=service.ListRecordingsReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_recordings(request) + client.list_transcripts(request) @pytest.mark.parametrize( "request_type", [ - service.ListRecordingsRequest, + service.ListTranscriptsRequest, dict, ], ) -def test_list_recordings_rest_call_success(request_type): +def test_list_transcripts_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10284,7 +11890,7 @@ def test_list_recordings_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListRecordingsResponse( + return_value = service.ListTranscriptsResponse( next_page_token="next_page_token_value", ) @@ -10293,20 +11899,20 @@ def test_list_recordings_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRecordingsResponse.pb(return_value) + return_value = service.ListTranscriptsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_recordings(request) + response = client.list_transcripts(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRecordingsPager) + assert isinstance(response, pagers.ListTranscriptsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_recordings_rest_interceptors(null_interceptor): +def test_list_transcripts_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10319,20 +11925,20 @@ def test_list_recordings_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_list_recordings" + transports.ConferenceRecordsServiceRestInterceptor, "post_list_transcripts" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_recordings_with_metadata", + "post_list_transcripts_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_list_recordings" + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_transcripts" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListRecordingsRequest.pb(service.ListRecordingsRequest()) + pb_message = service.ListTranscriptsRequest.pb(service.ListTranscriptsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10343,21 +11949,21 @@ def test_list_recordings_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListRecordingsResponse.to_json( - service.ListRecordingsResponse() + return_value = service.ListTranscriptsResponse.to_json( + service.ListTranscriptsResponse() ) req.return_value.content = return_value - request = service.ListRecordingsRequest() + request = service.ListTranscriptsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListRecordingsResponse() - post_with_metadata.return_value = service.ListRecordingsResponse(), metadata + post.return_value = service.ListTranscriptsResponse() + post_with_metadata.return_value = service.ListTranscriptsResponse(), metadata - client.list_recordings( + client.list_transcripts( request, metadata=[ ("key", "val"), @@ -10370,12 +11976,16 @@ def test_list_recordings_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_transcript_rest_bad_request(request_type=service.GetTranscriptRequest): +def test_get_transcript_entry_rest_bad_request( + request_type=service.GetTranscriptEntryRequest, +): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} + request_init = { + "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10391,31 +12001,35 @@ def test_get_transcript_rest_bad_request(request_type=service.GetTranscriptReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript(request) + client.get_transcript_entry(request) @pytest.mark.parametrize( "request_type", [ - service.GetTranscriptRequest, + service.GetTranscriptEntryRequest, dict, ], ) -def test_get_transcript_rest_call_success(request_type): +def test_get_transcript_entry_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} + request_init = { + "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Transcript( + return_value = resource.TranscriptEntry( name="name_value", - state=resource.Transcript.State.STARTED, + participant="participant_value", + text="text_value", + language_code="language_code_value", ) # Wrap the value into a proper Response obj @@ -10423,21 +12037,23 @@ def test_get_transcript_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Transcript.pb(return_value) + return_value = resource.TranscriptEntry.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript(request) + response = client.get_transcript_entry(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Transcript) + assert isinstance(response, resource.TranscriptEntry) assert response.name == "name_value" - assert response.state == resource.Transcript.State.STARTED + assert response.participant == "participant_value" + assert response.text == "text_value" + assert response.language_code == "language_code_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_transcript_rest_interceptors(null_interceptor): +def test_get_transcript_entry_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10450,20 +12066,24 @@ def test_get_transcript_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_get_transcript" + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_transcript_entry", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_transcript_with_metadata", + "post_get_transcript_entry_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_get_transcript" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_get_transcript_entry", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetTranscriptRequest.pb(service.GetTranscriptRequest()) + pb_message = service.GetTranscriptEntryRequest.pb( + service.GetTranscriptEntryRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10474,19 +12094,19 @@ def test_get_transcript_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Transcript.to_json(resource.Transcript()) + return_value = resource.TranscriptEntry.to_json(resource.TranscriptEntry()) req.return_value.content = return_value - request = service.GetTranscriptRequest() + request = service.GetTranscriptEntryRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Transcript() - post_with_metadata.return_value = resource.Transcript(), metadata + post.return_value = resource.TranscriptEntry() + post_with_metadata.return_value = resource.TranscriptEntry(), metadata - client.get_transcript( + client.get_transcript_entry( request, metadata=[ ("key", "val"), @@ -10499,12 +12119,14 @@ def test_get_transcript_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_transcripts_rest_bad_request(request_type=service.ListTranscriptsRequest): +def test_list_transcript_entries_rest_bad_request( + request_type=service.ListTranscriptEntriesRequest, +): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10520,29 +12142,29 @@ def test_list_transcripts_rest_bad_request(request_type=service.ListTranscriptsR response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcripts(request) + client.list_transcript_entries(request) @pytest.mark.parametrize( "request_type", [ - service.ListTranscriptsRequest, + service.ListTranscriptEntriesRequest, dict, ], ) -def test_list_transcripts_rest_call_success(request_type): +def test_list_transcript_entries_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptsResponse( + return_value = service.ListTranscriptEntriesResponse( next_page_token="next_page_token_value", ) @@ -10551,20 +12173,20 @@ def test_list_transcripts_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptsResponse.pb(return_value) + return_value = service.ListTranscriptEntriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcripts(request) + response = client.list_transcript_entries(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTranscriptsPager) + assert isinstance(response, pagers.ListTranscriptEntriesPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_transcripts_rest_interceptors(null_interceptor): +def test_list_transcript_entries_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10577,20 +12199,24 @@ def test_list_transcripts_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_list_transcripts" + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_transcript_entries", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_transcripts_with_metadata", + "post_list_transcript_entries_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_list_transcripts" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_list_transcript_entries", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListTranscriptsRequest.pb(service.ListTranscriptsRequest()) + pb_message = service.ListTranscriptEntriesRequest.pb( + service.ListTranscriptEntriesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10601,21 +12227,24 @@ def test_list_transcripts_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListTranscriptsResponse.to_json( - service.ListTranscriptsResponse() + return_value = service.ListTranscriptEntriesResponse.to_json( + service.ListTranscriptEntriesResponse() ) req.return_value.content = return_value - request = service.ListTranscriptsRequest() + request = service.ListTranscriptEntriesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListTranscriptsResponse() - post_with_metadata.return_value = service.ListTranscriptsResponse(), metadata + post.return_value = service.ListTranscriptEntriesResponse() + post_with_metadata.return_value = ( + service.ListTranscriptEntriesResponse(), + metadata, + ) - client.list_transcripts( + client.list_transcript_entries( request, metadata=[ ("key", "val"), @@ -10628,16 +12257,12 @@ def test_list_transcripts_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_transcript_entry_rest_bad_request( - request_type=service.GetTranscriptEntryRequest, -): +def test_get_smart_note_rest_bad_request(request_type=service.GetSmartNoteRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" - } + request_init = {"name": "conferenceRecords/sample1/smartNotes/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10653,35 +12278,31 @@ def test_get_transcript_entry_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript_entry(request) + client.get_smart_note(request) @pytest.mark.parametrize( "request_type", [ - service.GetTranscriptEntryRequest, + service.GetSmartNoteRequest, dict, ], ) -def test_get_transcript_entry_rest_call_success(request_type): +def test_get_smart_note_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" - } + request_init = {"name": "conferenceRecords/sample1/smartNotes/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.TranscriptEntry( + return_value = resource.SmartNote( name="name_value", - participant="participant_value", - text="text_value", - language_code="language_code_value", + state=resource.SmartNote.State.STARTED, ) # Wrap the value into a proper Response obj @@ -10689,23 +12310,21 @@ def test_get_transcript_entry_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.TranscriptEntry.pb(return_value) + return_value = resource.SmartNote.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript_entry(request) + response = client.get_smart_note(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.TranscriptEntry) + assert isinstance(response, resource.SmartNote) assert response.name == "name_value" - assert response.participant == "participant_value" - assert response.text == "text_value" - assert response.language_code == "language_code_value" + assert response.state == resource.SmartNote.State.STARTED @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_transcript_entry_rest_interceptors(null_interceptor): +def test_get_smart_note_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10718,24 +12337,20 @@ def test_get_transcript_entry_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_get_transcript_entry", + transports.ConferenceRecordsServiceRestInterceptor, "post_get_smart_note" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_transcript_entry_with_metadata", + "post_get_smart_note_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_get_transcript_entry", + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_smart_note" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetTranscriptEntryRequest.pb( - service.GetTranscriptEntryRequest() - ) + pb_message = service.GetSmartNoteRequest.pb(service.GetSmartNoteRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10746,19 +12361,19 @@ def test_get_transcript_entry_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.TranscriptEntry.to_json(resource.TranscriptEntry()) + return_value = resource.SmartNote.to_json(resource.SmartNote()) req.return_value.content = return_value - request = service.GetTranscriptEntryRequest() + request = service.GetSmartNoteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.TranscriptEntry() - post_with_metadata.return_value = resource.TranscriptEntry(), metadata + post.return_value = resource.SmartNote() + post_with_metadata.return_value = resource.SmartNote(), metadata - client.get_transcript_entry( + client.get_smart_note( request, metadata=[ ("key", "val"), @@ -10771,14 +12386,12 @@ def test_get_transcript_entry_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_transcript_entries_rest_bad_request( - request_type=service.ListTranscriptEntriesRequest, -): +def test_list_smart_notes_rest_bad_request(request_type=service.ListSmartNotesRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10794,29 +12407,29 @@ def test_list_transcript_entries_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcript_entries(request) + client.list_smart_notes(request) @pytest.mark.parametrize( "request_type", [ - service.ListTranscriptEntriesRequest, + service.ListSmartNotesRequest, dict, ], ) -def test_list_transcript_entries_rest_call_success(request_type): +def test_list_smart_notes_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptEntriesResponse( + return_value = service.ListSmartNotesResponse( next_page_token="next_page_token_value", ) @@ -10825,20 +12438,20 @@ def test_list_transcript_entries_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptEntriesResponse.pb(return_value) + return_value = service.ListSmartNotesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcript_entries(request) + response = client.list_smart_notes(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTranscriptEntriesPager) + assert isinstance(response, pagers.ListSmartNotesPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_transcript_entries_rest_interceptors(null_interceptor): +def test_list_smart_notes_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10851,24 +12464,20 @@ def test_list_transcript_entries_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_list_transcript_entries", + transports.ConferenceRecordsServiceRestInterceptor, "post_list_smart_notes" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_transcript_entries_with_metadata", + "post_list_smart_notes_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_list_transcript_entries", + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_smart_notes" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListTranscriptEntriesRequest.pb( - service.ListTranscriptEntriesRequest() - ) + pb_message = service.ListSmartNotesRequest.pb(service.ListSmartNotesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10879,24 +12488,21 @@ def test_list_transcript_entries_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListTranscriptEntriesResponse.to_json( - service.ListTranscriptEntriesResponse() + return_value = service.ListSmartNotesResponse.to_json( + service.ListSmartNotesResponse() ) req.return_value.content = return_value - request = service.ListTranscriptEntriesRequest() + request = service.ListSmartNotesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListTranscriptEntriesResponse() - post_with_metadata.return_value = ( - service.ListTranscriptEntriesResponse(), - metadata, - ) + post.return_value = service.ListSmartNotesResponse() + post_with_metadata.return_value = service.ListSmartNotesResponse(), metadata - client.list_transcript_entries( + client.list_smart_notes( request, metadata=[ ("key", "val"), @@ -11158,6 +12764,44 @@ def test_list_transcript_entries_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_smart_note_empty_call_rest(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + client.get_smart_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSmartNoteRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_smart_notes_empty_call_rest(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + client.list_smart_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ConferenceRecordsServiceClient( @@ -11203,6 +12847,8 @@ def test_conference_records_service_base_transport(): "list_transcripts", "get_transcript_entry", "list_transcript_entries", + "get_smart_note", + "list_smart_notes", ) for method in methods: with pytest.raises(NotImplementedError): @@ -11518,6 +13164,12 @@ def test_conference_records_service_client_transport_session_collision(transport session1 = client1.transport.list_transcript_entries._session session2 = client2.transport.list_transcript_entries._session assert session1 != session2 + session1 = client1.transport.get_smart_note._session + session2 = client2.transport.get_smart_note._session + assert session1 != session2 + session1 = client1.transport.list_smart_notes._session + session2 = client2.transport.list_smart_notes._session + assert session1 != session2 def test_conference_records_service_grpc_transport_channel(): @@ -11745,8 +13397,33 @@ def test_parse_recording_path(): assert expected == actual +def test_smart_note_path(): + conference_record = "oyster" + smart_note = "nudibranch" + expected = "conferenceRecords/{conference_record}/smartNotes/{smart_note}".format( + conference_record=conference_record, + smart_note=smart_note, + ) + actual = ConferenceRecordsServiceClient.smart_note_path( + conference_record, smart_note + ) + assert expected == actual + + +def test_parse_smart_note_path(): + expected = { + "conference_record": "cuttlefish", + "smart_note": "mussel", + } + path = ConferenceRecordsServiceClient.smart_note_path(**expected) + + # Check that the path construction is reversible. + actual = ConferenceRecordsServiceClient.parse_smart_note_path(path) + assert expected == actual + + def test_space_path(): - space = "oyster" + space = "winkle" expected = "spaces/{space}".format( space=space, ) @@ -11756,7 +13433,7 @@ def test_space_path(): def test_parse_space_path(): expected = { - "space": "nudibranch", + "space": "nautilus", } path = ConferenceRecordsServiceClient.space_path(**expected) @@ -11766,8 +13443,8 @@ def test_parse_space_path(): def test_transcript_path(): - conference_record = "cuttlefish" - transcript = "mussel" + conference_record = "scallop" + transcript = "abalone" expected = "conferenceRecords/{conference_record}/transcripts/{transcript}".format( conference_record=conference_record, transcript=transcript, @@ -11780,8 +13457,8 @@ def test_transcript_path(): def test_parse_transcript_path(): expected = { - "conference_record": "winkle", - "transcript": "nautilus", + "conference_record": "squid", + "transcript": "clam", } path = ConferenceRecordsServiceClient.transcript_path(**expected) @@ -11791,9 +13468,9 @@ def test_parse_transcript_path(): def test_transcript_entry_path(): - conference_record = "scallop" - transcript = "abalone" - entry = "squid" + conference_record = "whelk" + transcript = "octopus" + entry = "oyster" expected = "conferenceRecords/{conference_record}/transcripts/{transcript}/entries/{entry}".format( conference_record=conference_record, transcript=transcript, @@ -11807,9 +13484,9 @@ def test_transcript_entry_path(): def test_parse_transcript_entry_path(): expected = { - "conference_record": "clam", - "transcript": "whelk", - "entry": "octopus", + "conference_record": "nudibranch", + "transcript": "cuttlefish", + "entry": "mussel", } path = ConferenceRecordsServiceClient.transcript_entry_path(**expected) @@ -11819,7 +13496,7 @@ def test_parse_transcript_entry_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -11829,7 +13506,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "nautilus", } path = ConferenceRecordsServiceClient.common_billing_account_path(**expected) @@ -11839,7 +13516,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -11849,7 +13526,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "abalone", } path = ConferenceRecordsServiceClient.common_folder_path(**expected) @@ -11859,7 +13536,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -11869,7 +13546,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "clam", } path = ConferenceRecordsServiceClient.common_organization_path(**expected) @@ -11879,7 +13556,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -11889,7 +13566,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "octopus", } path = ConferenceRecordsServiceClient.common_project_path(**expected) @@ -11899,8 +13576,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -11911,8 +13588,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "cuttlefish", + "location": "mussel", } path = ConferenceRecordsServiceClient.common_location_path(**expected) diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py index b68d4036b588..c657c518ecfa 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py @@ -56,6 +56,7 @@ from google.apps.meet_v2.services.spaces_service import ( SpacesServiceAsyncClient, SpacesServiceClient, + pagers, transports, ) from google.apps.meet_v2.types import resource, service @@ -2318,13 +2319,82 @@ async def test_end_active_conference_flattened_error_async(): ) -def test_create_space_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMemberRequest(), + {}, + ], +) +def test_create_member(request_type, transport: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + response = client.create_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + + +def test_create_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateMemberRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMemberRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_member_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -2332,89 +2402,37 @@ def test_create_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_space in client._transport._wrapped_methods + assert client._transport.create_member in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_space] = mock_rpc - + client._transport._wrapped_methods[client._transport.create_member] = mock_rpc request = {} - client.create_space(request) + client.create_member(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_space(request) + client.create_member(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_space_rest_flattened(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resource.Space() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - space=resource.Space(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_space(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/spaces" % client.transport._host, args[1]) - - -def test_create_space_rest_flattened_error(transport: str = "rest"): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_space( - service.CreateSpaceRequest(), - space=resource.Space(name="name_value"), - ) - - -def test_get_space_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_create_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -2422,330 +2440,299 @@ def test_get_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_space in client._transport._wrapped_methods + assert ( + client._client._transport.create_member + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_space] = mock_rpc + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_member + ] = mock_rpc request = {} - client.get_space(request) + await client.create_member(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space(request) + await client.create_member(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): - transport_class = transports.SpacesServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMemberRequest(), + {}, + ], +) +async def test_create_member_async(request_type, transport: str = "grpc_asyncio"): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - default_values = getattr( - transport_class._BaseGetSpace, - "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + ) + response = await client.create_member(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateMemberRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_create_member_field_headers(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resource.Space() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateMemberRequest() - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + call.return_value = resource.Member() + client.create_member(request) - response = client.get_space(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_get_space_rest_flattened(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_create_member_field_headers_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resource.Space() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateMemberRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + await client.create_member(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_space(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_member_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_member( + parent="parent_value", + member=resource.Member(name="name_value"), + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=spaces/*}" % client.transport._host, args[1] - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].member + mock_val = resource.Member(name="name_value") + assert arg == mock_val -def test_get_space_rest_flattened_error(transport: str = "rest"): +def test_create_member_flattened_error(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_space( - service.GetSpaceRequest(), - name="name_value", + client.create_member( + service.CreateMemberRequest(), + parent="parent_value", + member=resource.Member(name="name_value"), ) -def test_update_space_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_create_member_flattened_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.update_space in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_member( + parent="parent_value", + member=resource.Member(name="name_value"), ) - client._transport._wrapped_methods[client._transport.update_space] = mock_rpc - - request = {} - client.update_space(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_space(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_space_rest_required_fields(request_type=service.UpdateSpaceRequest): - transport_class = transports.SpacesServiceRestTransport - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].member + mock_val = resource.Member(name="name_value") + assert arg == mock_val - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseUpdateSpace, - "_BaseUpdateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_create_member_flattened_error_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("updateMask",)) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_member( + service.CreateMemberRequest(), + parent="parent_value", + member=resource.Member(name="name_value"), + ) - # verify required fields with non-default values are left alone +@pytest.mark.parametrize( + "request_type", + [ + service.GetMemberRequest(), + {}, + ], +) +def test_get_member(request_type, transport: str = "grpc"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resource.Space() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + response = client.get_member(request) - response = client.update_space(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetMemberRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST -def test_update_space_rest_flattened(): +def test_get_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resource.Space() - - # get arguments that satisfy an http rule for this method - sample_request = {"space": {"name": "spaces/sample1"}} - - # get truthy value for each flattened field - mock_args = dict( - space=resource.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_space(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{space.name=spaces/*}" % client.transport._host, args[1] - ) - - -def test_update_space_rest_flattened_error(transport: str = "rest"): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetMemberRequest( + name="name_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_space( - service.UpdateSpaceRequest(), - space=resource.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMemberRequest( + name="name_value", ) + assert args[0] == request_msg -def test_end_active_conference_rest_use_cached_wrapped_rpc(): +def test_get_member_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -2753,484 +2740,4575 @@ def test_end_active_conference_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.end_active_conference - in client._transport._wrapped_methods - ) + assert client._transport.get_member in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.end_active_conference] = ( - mock_rpc - ) - + client._transport._wrapped_methods[client._transport.get_member] = mock_rpc request = {} - client.end_active_conference(request) + client.get_member(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.end_active_conference(request) + client.get_member(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_end_active_conference_rest_required_fields( - request_type=service.EndActiveConferenceRequest, -): - transport_class = transports.SpacesServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) +@pytest.mark.asyncio +async def test_get_member_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - default_values = getattr( - transport_class._BaseEndActiveConference, - "_BaseEndActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", + # Ensure method has been cached + assert ( + client._client._transport.get_member + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_member + ] = mock_rpc + + request = {} + await client.get_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.GetMemberRequest(), {}, + ], +) +async def test_get_member_async(request_type, transport: str = "grpc_asyncio"): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + ) + response = await client.get_member(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + +def test_get_member_field_headers(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetMemberRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = "" + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + call.return_value = resource.Member() + client.get_member(request) - response = client.end_active_conference(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_end_active_conference_rest_flattened(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_member_field_headers_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = None + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetMemberRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + await client.get_member(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.end_active_conference(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_member_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_member( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=spaces/*}:endActiveConference" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_end_active_conference_rest_flattened_error(transport: str = "rest"): +def test_get_member_flattened_error(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.end_active_conference( - service.EndActiveConferenceRequest(), + client.get_member( + service.GetMemberRequest(), name="name_value", ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SpacesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_get_member_flattened_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - with pytest.raises(ValueError): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.SpacesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SpacesServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() - # It is an error to provide an api_key and a transport instance. - transport = transports.SpacesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SpacesServiceClient( - client_options=options, - transport=transport, + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_member( + name="name_value", ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SpacesServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # It is an error to provide scopes and a transport instance. - transport = transports.SpacesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + +@pytest.mark.asyncio +async def test_get_member_flattened_error_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): - client = SpacesServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + await client.get_member( + service.GetMemberRequest(), + name="name_value", ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SpacesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SpacesServiceClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SpacesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SpacesServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.SpacesServiceGrpcTransport, - transports.SpacesServiceGrpcAsyncIOTransport, - transports.SpacesServiceRestTransport, + service.ListMembersRequest(), + {}, ], ) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_list_members(request_type, transport: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type -def test_transport_kind_grpc(): - transport = SpacesServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembersResponse( + next_page_token="next_page_token_value", + ) + response = client.list_members(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListMembersRequest() + assert args[0] == request -def test_initialize_client_w_grpc(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembersPager) + assert response.next_page_token == "next_page_token_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_space_empty_call_grpc(): +def test_list_members_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_space), "__call__") as call: - call.return_value = resource.Space() - client.create_space(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListMembersRequest( + parent="parent_value", + page_token="page_token_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_members(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.CreateSpaceRequest() + request_msg = service.ListMembersRequest( + parent="parent_value", + page_token="page_token_value", + ) assert args[0] == request_msg -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_space_empty_call_grpc(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_list_members_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_space), "__call__") as call: - call.return_value = resource.Space() - client.get_space(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetSpaceRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert client._transport.list_members in client._transport._wrapped_methods + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_members] = mock_rpc + request = {} + client.list_members(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_space_empty_call_grpc(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_space), "__call__") as call: - call.return_value = resource.Space() - client.update_space(request=None) + client.list_members(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateSpaceRequest() - assert args[0] == request_msg + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_end_active_conference_empty_call_grpc(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +@pytest.mark.asyncio +async def test_list_members_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.end_active_conference), "__call__" - ) as call: - call.return_value = None - client.end_active_conference(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.EndActiveConferenceRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._client._transport.list_members + in client._client._transport._wrapped_methods + ) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_members + ] = mock_rpc -def test_transport_kind_grpc_asyncio(): - transport = SpacesServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + request = {} + await client.list_members(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_initialize_client_w_grpc_asyncio(): - client = SpacesServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + await client.list_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_create_space_empty_call_grpc_asyncio(): +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembersRequest(), + {}, + ], +) +async def test_list_members_async(request_type, transport: str = "grpc_asyncio"): client = SpacesServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_space), "__call__") as call: + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.Space( - name="name_value", - meeting_uri="meeting_uri_value", - meeting_code="meeting_code_value", + service.ListMembersResponse( + next_page_token="next_page_token_value", ) ) - await client.create_space(request=None) + response = await client.list_members(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.CreateSpaceRequest() - assert args[0] == request_msg + request = service.ListMembersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembersAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_members_field_headers(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + call.return_value = service.ListMembersResponse() + client.list_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_space_empty_call_grpc_asyncio(): +async def test_list_members_field_headers_async(): client = SpacesServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_space), "__call__") as call: - # Designate an appropriate return value for the call. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.Space( - name="name_value", - meeting_uri="meeting_uri_value", - meeting_code="meeting_code_value", - ) + service.ListMembersResponse() ) - await client.get_space(request=None) + await client.list_members(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.GetSpaceRequest() - assert args[0] == request_msg + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_members_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_members( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_members_flattened_error(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_members( + service.ListMembersRequest(), + parent="parent_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_update_space_empty_call_grpc_asyncio(): +async def test_list_members_flattened_async(): client = SpacesServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_space), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: # Designate an appropriate return value for the call. + call.return_value = service.ListMembersResponse() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.Space( - name="name_value", - meeting_uri="meeting_uri_value", - meeting_code="meeting_code_value", - ) + service.ListMembersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_members( + parent="parent_value", ) - await client.update_space(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.UpdateSpaceRequest() - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_end_active_conference_empty_call_grpc_asyncio(): +async def test_list_members_flattened_error_async(): client = SpacesServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_members( + service.ListMembersRequest(), + parent="parent_value", + ) + + +def test_list_members_pager(transport_name: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + resource.Member(), + ], + next_page_token="abc", + ), + service.ListMembersResponse( + members=[], + next_page_token="def", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + ], + next_page_token="ghi", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_members(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.Member) for i in results) + + +def test_list_members_pages(transport_name: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + resource.Member(), + ], + next_page_token="abc", + ), + service.ListMembersResponse( + members=[], + next_page_token="def", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + ], + next_page_token="ghi", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + ], + ), + RuntimeError, + ) + pages = list(client.list_members(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_members_async_pager(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.end_active_conference), "__call__" + type(client.transport.list_members), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + resource.Member(), + ], + next_page_token="abc", + ), + service.ListMembersResponse( + members=[], + next_page_token="def", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + ], + next_page_token="ghi", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_members( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resource.Member) for i in responses) + + +@pytest.mark.asyncio +async def test_list_members_async_pages(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_members), "__call__", new_callable=mock.AsyncMock ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + resource.Member(), + ], + next_page_token="abc", + ), + service.ListMembersResponse( + members=[], + next_page_token="def", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + ], + next_page_token="ghi", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_members(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteMemberRequest(), + {}, + ], +) +def test_delete_member(request_type, transport: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.end_active_conference(request=None) + call.return_value = None + response = client.delete_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteMemberRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMemberRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_member_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_member in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_member] = mock_rpc + request = {} + client.delete_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_member + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_member + ] = mock_rpc + + request = {} + await client.delete_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteMemberRequest(), + {}, + ], +) +async def test_delete_member_async(request_type, transport: str = "grpc_asyncio"): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_member_field_headers(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteMemberRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + call.return_value = None + client.delete_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_member_field_headers_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteMemberRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_member_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_member( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_member_flattened_error(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_member( + service.DeleteMemberRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_member_flattened_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_member( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_member_flattened_error_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_member( + service.DeleteMemberRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMemberRequest(), + {}, + ], +) +def test_update_member(request_type, transport: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + response = client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + + +def test_update_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateMemberRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +def test_update_member_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_member in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_member] = mock_rpc + request = {} + client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_member + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_member + ] = mock_rpc + + request = {} + await client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMemberRequest(), + {}, + ], +) +async def test_update_member_async(request_type, transport: str = "grpc_asyncio"): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + ) + response = await client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + + +def test_update_member_field_headers(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMemberRequest() + + request.member.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value = resource.Member() + client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "member.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_member_field_headers_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMemberRequest() + + request.member.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + await client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "member.name=name_value", + ) in kw["metadata"] + + +def test_update_member_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_member( + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].member + mock_val = resource.Member(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_member_flattened_error(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_member( + service.UpdateMemberRequest(), + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_member_flattened_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_member( + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].member + mock_val = resource.Member(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_member_flattened_error_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_member( + service.UpdateMemberRequest(), + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.BatchUpdateMembersRequest(), + {}, + ], +) +def test_batch_update_members(request_type, transport: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.BatchUpdateMembersResponse() + response = client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.BatchUpdateMembersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.BatchUpdateMembersResponse) + + +def test_batch_update_members_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_update_members(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_batch_update_members_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_update_members in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.batch_update_members] = ( + mock_rpc + ) + request = {} + client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_update_members_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_update_members + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_update_members + ] = mock_rpc + + request = {} + await client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_update_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.BatchUpdateMembersRequest(), + {}, + ], +) +async def test_batch_update_members_async( + request_type, transport: str = "grpc_asyncio" +): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.BatchUpdateMembersResponse() + ) + response = await client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.BatchUpdateMembersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.BatchUpdateMembersResponse) + + +def test_batch_update_members_field_headers(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchUpdateMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value = service.BatchUpdateMembersResponse() + client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_update_members_field_headers_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchUpdateMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.BatchUpdateMembersResponse() + ) + await client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_space_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_space in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_space] = mock_rpc + + request = {} + client.create_space(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_space(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_space_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + space=resource.Space(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/spaces" % client.transport._host, args[1]) + + +def test_create_space_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_space( + service.CreateSpaceRequest(), + space=resource.Space(name="name_value"), + ) + + +def test_get_space_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_space in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_space] = mock_rpc + + request = {} + client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_space(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetSpace, + "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_space_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=spaces/*}" % client.transport._host, args[1] + ) + + +def test_get_space_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_space( + service.GetSpaceRequest(), + name="name_value", + ) + + +def test_update_space_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_space in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_space] = mock_rpc + + request = {} + client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_space(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_space_rest_required_fields(request_type=service.UpdateSpaceRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateSpace, + "_BaseUpdateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_space_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {"space": {"name": "spaces/sample1"}} + + # get truthy value for each flattened field + mock_args = dict( + space=resource.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{space.name=spaces/*}" % client.transport._host, args[1] + ) + + +def test_update_space_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_space( + service.UpdateSpaceRequest(), + space=resource.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_end_active_conference_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.end_active_conference + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.end_active_conference] = ( + mock_rpc + ) + + request = {} + client.end_active_conference(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.end_active_conference(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_end_active_conference_rest_required_fields( + request_type=service.EndActiveConferenceRequest, +): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseEndActiveConference, + "_BaseEndActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.end_active_conference(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_end_active_conference_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.end_active_conference(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=spaces/*}:endActiveConference" % client.transport._host, + args[1], + ) + + +def test_end_active_conference_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.end_active_conference( + service.EndActiveConferenceRequest(), + name="name_value", + ) + + +def test_create_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_member in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_member] = mock_rpc + + request = {} + client.create_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_member_rest_required_fields(request_type=service.CreateMemberRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateMember, + "_BaseCreateMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.Member() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_member_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Member() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + member=resource.Member(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=spaces/*}/members" % client.transport._host, args[1] + ) + + +def test_create_member_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_member( + service.CreateMemberRequest(), + parent="parent_value", + member=resource.Member(name="name_value"), + ) + + +def test_get_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_member in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_member] = mock_rpc + + request = {} + client.get_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_member_rest_required_fields(request_type=service.GetMemberRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetMember, + "_BaseGetMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.Member() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_member_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Member() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/members/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=spaces/*/members/*}" % client.transport._host, args[1] + ) + + +def test_get_member_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_member( + service.GetMemberRequest(), + name="name_value", + ) + + +def test_list_members_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_members in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_members] = mock_rpc + + request = {} + client.list_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_members_rest_required_fields(request_type=service.ListMembersRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListMembers, + "_BaseListMembers__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListMembersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_members(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_members_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListMembersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_members(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=spaces/*}/members" % client.transport._host, args[1] + ) + + +def test_list_members_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_members( + service.ListMembersRequest(), + parent="parent_value", + ) + + +def test_list_members_rest_pager(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + resource.Member(), + ], + next_page_token="abc", + ), + service.ListMembersResponse( + members=[], + next_page_token="def", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + ], + next_page_token="ghi", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListMembersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "spaces/sample1"} + + pager = client.list_members(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.Member) for i in results) + + pages = list(client.list_members(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_member in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_member] = mock_rpc + + request = {} + client.delete_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_member_rest_required_fields(request_type=service.DeleteMemberRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteMember, + "_BaseDeleteMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_member_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/members/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=spaces/*/members/*}" % client.transport._host, args[1] + ) + + +def test_delete_member_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_member( + service.DeleteMemberRequest(), + name="name_value", + ) + + +def test_update_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_member in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_member] = mock_rpc + + request = {} + client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_member_rest_required_fields(request_type=service.UpdateMemberRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateMember, + "_BaseUpdateMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.Member() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_member_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Member() + + # get arguments that satisfy an http rule for this method + sample_request = {"member": {"name": "spaces/sample1/members/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{member.name=spaces/*/members/*}" % client.transport._host, args[1] + ) + + +def test_update_member_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_member( + service.UpdateMemberRequest(), + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_batch_update_members_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_update_members in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.batch_update_members] = ( + mock_rpc + ) + + request = {} + client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_update_members_rest_required_fields( + request_type=service.BatchUpdateMembersRequest, +): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseBatchUpdateMembers, + "_BaseBatchUpdateMembers__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.BatchUpdateMembersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.BatchUpdateMembersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_update_members(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SpacesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SpacesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SpacesServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SpacesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SpacesServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SpacesServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SpacesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SpacesServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SpacesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SpacesServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SpacesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SpacesServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SpacesServiceGrpcTransport, + transports.SpacesServiceGrpcAsyncIOTransport, + transports.SpacesServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = SpacesServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_space_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_space), "__call__") as call: + call.return_value = resource.Space() + client.create_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateSpaceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_space_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + call.return_value = resource.Space() + client.get_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSpaceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_space_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + call.return_value = resource.Space() + client.update_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateSpaceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_end_active_conference_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.end_active_conference), "__call__" + ) as call: + call.return_value = None + client.end_active_conference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EndActiveConferenceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_member_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + call.return_value = resource.Member() + client.create_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_member_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + call.return_value = resource.Member() + client.get_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_members_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + call.return_value = service.ListMembersResponse() + client.list_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_member_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + call.return_value = None + client.delete_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_member_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value = resource.Member() + client.update_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_members_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value = service.BatchUpdateMembersResponse() + client.batch_update_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SpacesServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_space_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Space( + name="name_value", + meeting_uri="meeting_uri_value", + meeting_code="meeting_code_value", + ) + ) + await client.create_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateSpaceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_space_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Space( + name="name_value", + meeting_uri="meeting_uri_value", + meeting_code="meeting_code_value", + ) + ) + await client.get_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSpaceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_space_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Space( + name="name_value", + meeting_uri="meeting_uri_value", + meeting_code="meeting_code_value", + ) + ) + await client.update_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateSpaceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_end_active_conference_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.end_active_conference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.end_active_conference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EndActiveConferenceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_member_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + ) + await client.create_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_member_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + ) + await client.get_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_members_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_member_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_member_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + ) + await client.update_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_update_members_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.BatchUpdateMembersResponse() + ) + await client.batch_update_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SpacesServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_space_rest_bad_request(request_type=service.CreateSpaceRequest): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_space(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateSpaceRequest, + dict, + ], +) +def test_create_space_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["space"] = { + "name": "name_value", + "meeting_uri": "meeting_uri_value", + "meeting_code": "meeting_code_value", + "config": { + "access_type": 1, + "entry_point_access": 1, + "moderation": 1, + "moderation_restrictions": { + "chat_restriction": 1, + "reaction_restriction": 1, + "present_restriction": 1, + "default_join_as_viewer_type": 1, + }, + "attendance_report_generation_type": 1, + "artifact_config": { + "recording_config": {"auto_recording_generation": 1}, + "transcription_config": {"auto_transcription_generation": 1}, + "smart_notes_config": {"auto_smart_notes_generation": 1}, + }, + }, + "active_conference": {"conference_record": "conference_record_value"}, + "phone_access": [ + { + "phone_number": "phone_number_value", + "pin": "pin_value", + "region_code": "region_code_value", + "language_code": "language_code_value", + } + ], + "gateway_sip_access": [ + {"uri": "uri_value", "sip_access_code": "sip_access_code_value"} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateSpaceRequest.meta.fields["space"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["space"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space( + name="name_value", + meeting_uri="meeting_uri_value", + meeting_code="meeting_code_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Space) + assert response.name == "name_value" + assert response.meeting_uri == "meeting_uri_value" + assert response.meeting_code == "meeting_code_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_space_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_create_space" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_create_space_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_create_space" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateSpaceRequest.pb(service.CreateSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.Space.to_json(resource.Space()) + req.return_value.content = return_value + + request = service.CreateSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.Space() + post_with_metadata.return_value = resource.Space(), metadata + + client.create_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_space_rest_bad_request(request_type=service.GetSpaceRequest): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_space(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetSpaceRequest, + dict, + ], +) +def test_get_space_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space( + name="name_value", + meeting_uri="meeting_uri_value", + meeting_code="meeting_code_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Space) + assert response.name == "name_value" + assert response.meeting_uri == "meeting_uri_value" + assert response.meeting_code == "meeting_code_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_space_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_get_space" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_get_space_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_get_space" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetSpaceRequest.pb(service.GetSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.Space.to_json(resource.Space()) + req.return_value.content = return_value + + request = service.GetSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.Space() + post_with_metadata.return_value = resource.Space(), metadata + + client.get_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_space_rest_bad_request(request_type=service.UpdateSpaceRequest): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"space": {"name": "spaces/sample1"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_space(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateSpaceRequest, + dict, + ], +) +def test_update_space_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"space": {"name": "spaces/sample1"}} + request_init["space"] = { + "name": "spaces/sample1", + "meeting_uri": "meeting_uri_value", + "meeting_code": "meeting_code_value", + "config": { + "access_type": 1, + "entry_point_access": 1, + "moderation": 1, + "moderation_restrictions": { + "chat_restriction": 1, + "reaction_restriction": 1, + "present_restriction": 1, + "default_join_as_viewer_type": 1, + }, + "attendance_report_generation_type": 1, + "artifact_config": { + "recording_config": {"auto_recording_generation": 1}, + "transcription_config": {"auto_transcription_generation": 1}, + "smart_notes_config": {"auto_smart_notes_generation": 1}, + }, + }, + "active_conference": {"conference_record": "conference_record_value"}, + "phone_access": [ + { + "phone_number": "phone_number_value", + "pin": "pin_value", + "region_code": "region_code_value", + "language_code": "language_code_value", + } + ], + "gateway_sip_access": [ + {"uri": "uri_value", "sip_access_code": "sip_access_code_value"} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateSpaceRequest.meta.fields["space"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["space"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space( + name="name_value", + meeting_uri="meeting_uri_value", + meeting_code="meeting_code_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Space) + assert response.name == "name_value" + assert response.meeting_uri == "meeting_uri_value" + assert response.meeting_code == "meeting_code_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_space_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_update_space" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_update_space_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_update_space" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateSpaceRequest.pb(service.UpdateSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.Space.to_json(resource.Space()) + req.return_value.content = return_value + + request = service.UpdateSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.Space() + post_with_metadata.return_value = resource.Space(), metadata + + client.update_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_end_active_conference_rest_bad_request( + request_type=service.EndActiveConferenceRequest, +): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.end_active_conference(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.EndActiveConferenceRequest, + dict, + ], +) +def test_end_active_conference_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.end_active_conference(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_end_active_conference_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_end_active_conference" + ) as pre, + ): + pre.assert_not_called() + pb_message = service.EndActiveConferenceRequest.pb( + service.EndActiveConferenceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.EndActiveConferenceRequest() - assert args[0] == request_msg + request = service.EndActiveConferenceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + client.end_active_conference( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = SpacesServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() -def test_create_space_rest_bad_request(request_type=service.CreateSpaceRequest): +def test_create_member_rest_bad_request(request_type=service.CreateMemberRequest): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3246,36 +7324,30 @@ def test_create_space_rest_bad_request(request_type=service.CreateSpaceRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_space(request) + client.create_member(request) @pytest.mark.parametrize( "request_type", [ - service.CreateSpaceRequest, + service.CreateMemberRequest, dict, ], ) -def test_create_space_rest_call_success(request_type): +def test_create_member_rest_call_success(request_type): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} - request_init["space"] = { - "name": "name_value", - "meeting_uri": "meeting_uri_value", - "meeting_code": "meeting_code_value", - "config": {"access_type": 1, "entry_point_access": 1}, - "active_conference": {"conference_record": "conference_record_value"}, - } + request_init = {"parent": "spaces/sample1"} + request_init["member"] = {"name": "name_value", "email": "email_value", "role": 1} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.CreateSpaceRequest.meta.fields["space"] + test_field = service.CreateMemberRequest.meta.fields["member"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -3303,7 +7375,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["space"].items(): # pragma: NO COVER + for field, value in request_init["member"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -3325,27 +7397,285 @@ def get_message_fields(field): } ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["space"][field])): - del request_init["space"][field][i][subfield] - else: - del request_init["space"][field][subfield] + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["member"][field])): + del request_init["member"][field][i][subfield] + else: + del request_init["member"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_member(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_member_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_create_member" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_create_member_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_create_member" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateMemberRequest.pb(service.CreateMemberRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.Member.to_json(resource.Member()) + req.return_value.content = return_value + + request = service.CreateMemberRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.Member() + post_with_metadata.return_value = resource.Member(), metadata + + client.create_member( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_member_rest_bad_request(request_type=service.GetMemberRequest): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_member(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetMemberRequest, + dict, + ], +) +def test_get_member_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_member(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_member_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_get_member" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_get_member_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_get_member" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetMemberRequest.pb(service.GetMemberRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.Member.to_json(resource.Member()) + req.return_value.content = return_value + + request = service.GetMemberRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.Member() + post_with_metadata.return_value = resource.Member(), metadata + + client.get_member( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_members_rest_bad_request(request_type=service.ListMembersRequest): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_members(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembersRequest, + dict, + ], +) +def test_list_members_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Space( - name="name_value", - meeting_uri="meeting_uri_value", - meeting_code="meeting_code_value", + return_value = service.ListMembersResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -3353,22 +7683,20 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) + return_value = service.ListMembersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_space(request) + response = client.list_members(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Space) - assert response.name == "name_value" - assert response.meeting_uri == "meeting_uri_value" - assert response.meeting_code == "meeting_code_value" + assert isinstance(response, pagers.ListMembersPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_space_rest_interceptors(null_interceptor): +def test_list_members_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3381,19 +7709,19 @@ def test_create_space_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_create_space" + transports.SpacesServiceRestInterceptor, "post_list_members" ) as post, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_create_space_with_metadata" + transports.SpacesServiceRestInterceptor, "post_list_members_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_create_space" + transports.SpacesServiceRestInterceptor, "pre_list_members" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateSpaceRequest.pb(service.CreateSpaceRequest()) + pb_message = service.ListMembersRequest.pb(service.ListMembersRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3404,19 +7732,21 @@ def test_create_space_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Space.to_json(resource.Space()) + return_value = service.ListMembersResponse.to_json( + service.ListMembersResponse() + ) req.return_value.content = return_value - request = service.CreateSpaceRequest() + request = service.ListMembersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Space() - post_with_metadata.return_value = resource.Space(), metadata + post.return_value = service.ListMembersResponse() + post_with_metadata.return_value = service.ListMembersResponse(), metadata - client.create_space( + client.list_members( request, metadata=[ ("key", "val"), @@ -3429,12 +7759,12 @@ def test_create_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_space_rest_bad_request(request_type=service.GetSpaceRequest): +def test_delete_member_rest_bad_request(request_type=service.DeleteMemberRequest): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"name": "spaces/sample1/members/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3450,55 +7780,45 @@ def test_get_space_rest_bad_request(request_type=service.GetSpaceRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_space(request) + client.delete_member(request) @pytest.mark.parametrize( "request_type", [ - service.GetSpaceRequest, + service.DeleteMemberRequest, dict, ], ) -def test_get_space_rest_call_success(request_type): +def test_delete_member_rest_call_success(request_type): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"name": "spaces/sample1/members/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Space( - name="name_value", - meeting_uri="meeting_uri_value", - meeting_code="meeting_code_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_space(request) + response = client.delete_member(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Space) - assert response.name == "name_value" - assert response.meeting_uri == "meeting_uri_value" - assert response.meeting_code == "meeting_code_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_space_rest_interceptors(null_interceptor): +def test_delete_member_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3511,19 +7831,11 @@ def test_get_space_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_get_space" - ) as post, - mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_get_space_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_get_space" + transports.SpacesServiceRestInterceptor, "pre_delete_member" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.GetSpaceRequest.pb(service.GetSpaceRequest()) + pb_message = service.DeleteMemberRequest.pb(service.DeleteMemberRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3534,19 +7846,15 @@ def test_get_space_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Space.to_json(resource.Space()) - req.return_value.content = return_value - request = service.GetSpaceRequest() + request = service.DeleteMemberRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Space() - post_with_metadata.return_value = resource.Space(), metadata - client.get_space( + client.delete_member( request, metadata=[ ("key", "val"), @@ -3555,16 +7863,14 @@ def test_get_space_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_update_space_rest_bad_request(request_type=service.UpdateSpaceRequest): +def test_update_member_rest_bad_request(request_type=service.UpdateMemberRequest): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"space": {"name": "spaces/sample1"}} + request_init = {"member": {"name": "spaces/sample1/members/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3580,36 +7886,34 @@ def test_update_space_rest_bad_request(request_type=service.UpdateSpaceRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_space(request) + client.update_member(request) @pytest.mark.parametrize( "request_type", [ - service.UpdateSpaceRequest, + service.UpdateMemberRequest, dict, ], ) -def test_update_space_rest_call_success(request_type): +def test_update_member_rest_call_success(request_type): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"space": {"name": "spaces/sample1"}} - request_init["space"] = { - "name": "spaces/sample1", - "meeting_uri": "meeting_uri_value", - "meeting_code": "meeting_code_value", - "config": {"access_type": 1, "entry_point_access": 1}, - "active_conference": {"conference_record": "conference_record_value"}, + request_init = {"member": {"name": "spaces/sample1/members/sample2"}} + request_init["member"] = { + "name": "spaces/sample1/members/sample2", + "email": "email_value", + "role": 1, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateSpaceRequest.meta.fields["space"] + test_field = service.UpdateMemberRequest.meta.fields["member"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -3637,7 +7941,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["space"].items(): # pragma: NO COVER + for field, value in request_init["member"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -3667,19 +7971,19 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["space"][field])): - del request_init["space"][field][i][subfield] + for i in range(0, len(request_init["member"][field])): + del request_init["member"][field][i][subfield] else: - del request_init["space"][field][subfield] + del request_init["member"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Space( + return_value = resource.Member( name="name_value", - meeting_uri="meeting_uri_value", - meeting_code="meeting_code_value", + email="email_value", + role=resource.Member.Role.COHOST, ) # Wrap the value into a proper Response obj @@ -3687,22 +7991,22 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) + return_value = resource.Member.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_space(request) + response = client.update_member(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Space) + assert isinstance(response, resource.Member) assert response.name == "name_value" - assert response.meeting_uri == "meeting_uri_value" - assert response.meeting_code == "meeting_code_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_space_rest_interceptors(null_interceptor): +def test_update_member_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3715,19 +8019,19 @@ def test_update_space_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_update_space" + transports.SpacesServiceRestInterceptor, "post_update_member" ) as post, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_update_space_with_metadata" + transports.SpacesServiceRestInterceptor, "post_update_member_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_update_space" + transports.SpacesServiceRestInterceptor, "pre_update_member" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.UpdateSpaceRequest.pb(service.UpdateSpaceRequest()) + pb_message = service.UpdateMemberRequest.pb(service.UpdateMemberRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3738,19 +8042,19 @@ def test_update_space_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Space.to_json(resource.Space()) + return_value = resource.Member.to_json(resource.Member()) req.return_value.content = return_value - request = service.UpdateSpaceRequest() + request = service.UpdateMemberRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Space() - post_with_metadata.return_value = resource.Space(), metadata + post.return_value = resource.Member() + post_with_metadata.return_value = resource.Member(), metadata - client.update_space( + client.update_member( request, metadata=[ ("key", "val"), @@ -3763,14 +8067,14 @@ def test_update_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_end_active_conference_rest_bad_request( - request_type=service.EndActiveConferenceRequest, +def test_batch_update_members_rest_bad_request( + request_type=service.BatchUpdateMembersRequest, ): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3786,45 +8090,48 @@ def test_end_active_conference_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.end_active_conference(request) + client.batch_update_members(request) @pytest.mark.parametrize( "request_type", [ - service.EndActiveConferenceRequest, + service.BatchUpdateMembersRequest, dict, ], ) -def test_end_active_conference_rest_call_success(request_type): +def test_batch_update_members_rest_call_success(request_type): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = service.BatchUpdateMembersResponse() # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = service.BatchUpdateMembersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.end_active_conference(request) + response = client.batch_update_members(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, service.BatchUpdateMembersResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_end_active_conference_rest_interceptors(null_interceptor): +def test_batch_update_members_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3837,12 +8144,21 @@ def test_end_active_conference_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_end_active_conference" + transports.SpacesServiceRestInterceptor, "post_batch_update_members" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, + "post_batch_update_members_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_batch_update_members" ) as pre, ): pre.assert_not_called() - pb_message = service.EndActiveConferenceRequest.pb( - service.EndActiveConferenceRequest() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.BatchUpdateMembersRequest.pb( + service.BatchUpdateMembersRequest() ) transcode.return_value = { "method": "post", @@ -3854,15 +8170,21 @@ def test_end_active_conference_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.BatchUpdateMembersResponse.to_json( + service.BatchUpdateMembersResponse() + ) + req.return_value.content = return_value - request = service.EndActiveConferenceRequest() + request = service.BatchUpdateMembersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = service.BatchUpdateMembersResponse() + post_with_metadata.return_value = service.BatchUpdateMembersResponse(), metadata - client.end_active_conference( + client.batch_update_members( request, metadata=[ ("key", "val"), @@ -3871,6 +8193,8 @@ def test_end_active_conference_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() def test_initialize_client_w_rest(): @@ -3958,6 +8282,122 @@ def test_end_active_conference_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_member_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_member), "__call__") as call: + client.create_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_member_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_member), "__call__") as call: + client.get_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_members_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_members), "__call__") as call: + client.list_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_member_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_member), "__call__") as call: + client.delete_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_member_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + client.update_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_members_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + client.batch_update_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SpacesServiceClient( @@ -3995,6 +8435,12 @@ def test_spaces_service_base_transport(): "get_space", "update_space", "end_active_conference", + "create_member", + "get_member", + "list_members", + "delete_member", + "update_member", + "batch_update_members", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4286,6 +8732,24 @@ def test_spaces_service_client_transport_session_collision(transport_name): session1 = client1.transport.end_active_conference._session session2 = client2.transport.end_active_conference._session assert session1 != session2 + session1 = client1.transport.create_member._session + session2 = client2.transport.create_member._session + assert session1 != session2 + session1 = client1.transport.get_member._session + session2 = client2.transport.get_member._session + assert session1 != session2 + session1 = client1.transport.list_members._session + session2 = client2.transport.list_members._session + assert session1 != session2 + session1 = client1.transport.delete_member._session + session2 = client2.transport.delete_member._session + assert session1 != session2 + session1 = client1.transport.update_member._session + session2 = client2.transport.update_member._session + assert session1 != session2 + session1 = client1.transport.batch_update_members._session + session2 = client2.transport.batch_update_members._session + assert session1 != session2 def test_spaces_service_grpc_transport_channel(): @@ -4433,8 +8897,31 @@ def test_parse_conference_record_path(): assert expected == actual -def test_space_path(): +def test_member_path(): space = "whelk" + member = "octopus" + expected = "spaces/{space}/members/{member}".format( + space=space, + member=member, + ) + actual = SpacesServiceClient.member_path(space, member) + assert expected == actual + + +def test_parse_member_path(): + expected = { + "space": "oyster", + "member": "nudibranch", + } + path = SpacesServiceClient.member_path(**expected) + + # Check that the path construction is reversible. + actual = SpacesServiceClient.parse_member_path(path) + assert expected == actual + + +def test_space_path(): + space = "cuttlefish" expected = "spaces/{space}".format( space=space, ) @@ -4444,7 +8931,7 @@ def test_space_path(): def test_parse_space_path(): expected = { - "space": "octopus", + "space": "mussel", } path = SpacesServiceClient.space_path(**expected) @@ -4454,7 +8941,7 @@ def test_parse_space_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4464,7 +8951,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "nautilus", } path = SpacesServiceClient.common_billing_account_path(**expected) @@ -4474,7 +8961,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -4484,7 +8971,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "abalone", } path = SpacesServiceClient.common_folder_path(**expected) @@ -4494,7 +8981,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -4504,7 +8991,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "clam", } path = SpacesServiceClient.common_organization_path(**expected) @@ -4514,7 +9001,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -4524,7 +9011,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "octopus", } path = SpacesServiceClient.common_project_path(**expected) @@ -4534,8 +9021,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -4546,8 +9033,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "cuttlefish", + "location": "mussel", } path = SpacesServiceClient.common_location_path(**expected) diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py index 0dba85a72c10..ca917887eb43 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py @@ -6234,6 +6234,853 @@ async def test_list_transcript_entries_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + service.GetSmartNoteRequest(), + {}, + ], +) +def test_get_smart_note(request_type, transport: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.SmartNote( + name="name_value", + state=resource.SmartNote.State.STARTED, + ) + response = client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetSmartNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.SmartNote) + assert response.name == "name_value" + assert response.state == resource.SmartNote.State.STARTED + + +def test_get_smart_note_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetSmartNoteRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_smart_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSmartNoteRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_smart_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_smart_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_smart_note] = mock_rpc + request = {} + client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_smart_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_smart_note_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_smart_note + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_smart_note + ] = mock_rpc + + request = {} + await client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_smart_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.GetSmartNoteRequest(), + {}, + ], +) +async def test_get_smart_note_async(request_type, transport: str = "grpc_asyncio"): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.SmartNote( + name="name_value", + state=resource.SmartNote.State.STARTED, + ) + ) + response = await client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetSmartNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.SmartNote) + assert response.name == "name_value" + assert response.state == resource.SmartNote.State.STARTED + + +def test_get_smart_note_field_headers(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSmartNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value = resource.SmartNote() + client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_smart_note_field_headers_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetSmartNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.SmartNote()) + await client.get_smart_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_smart_note_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.SmartNote() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_smart_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_smart_note_flattened_error(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_smart_note( + service.GetSmartNoteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_smart_note_flattened_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.SmartNote() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.SmartNote()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_smart_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_smart_note_flattened_error_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_smart_note( + service.GetSmartNoteRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListSmartNotesRequest(), + {}, + ], +) +def test_list_smart_notes(request_type, transport: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSmartNotesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListSmartNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSmartNotesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_smart_notes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListSmartNotesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_smart_notes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_smart_notes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_smart_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_smart_notes] = ( + mock_rpc + ) + request = {} + client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_smart_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_smart_notes_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_smart_notes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_smart_notes + ] = mock_rpc + + request = {} + await client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_smart_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.ListSmartNotesRequest(), + {}, + ], +) +async def test_list_smart_notes_async(request_type, transport: str = "grpc_asyncio"): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSmartNotesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListSmartNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSmartNotesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_smart_notes_field_headers(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSmartNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value = service.ListSmartNotesResponse() + client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_smart_notes_field_headers_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListSmartNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSmartNotesResponse() + ) + await client.list_smart_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_smart_notes_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSmartNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_smart_notes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_smart_notes_flattened_error(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_smart_notes( + service.ListSmartNotesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_smart_notes_flattened_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSmartNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSmartNotesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_smart_notes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_smart_notes_flattened_error_async(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_smart_notes( + service.ListSmartNotesRequest(), + parent="parent_value", + ) + + +def test_list_smart_notes_pager(transport_name: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_smart_notes(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.SmartNote) for i in results) + + +def test_list_smart_notes_pages(transport_name: str = "grpc"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + pages = list(client.list_smart_notes(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_smart_notes_async_pager(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_smart_notes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_smart_notes( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resource.SmartNote) for i in responses) + + +@pytest.mark.asyncio +async def test_list_smart_notes_async_pages(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_smart_notes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), + ], + next_page_token="abc", + ), + service.ListSmartNotesResponse( + smart_notes=[], + next_page_token="def", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + ], + next_page_token="ghi", + ), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_smart_notes(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_get_conference_record_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6248,35 +7095,309 @@ def test_get_conference_record_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_conference_record - in client._transport._wrapped_methods - ) + assert ( + client._transport.get_conference_record + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_conference_record] = ( + mock_rpc + ) + + request = {} + client.get_conference_record(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conference_record(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_conference_record_rest_required_fields( + request_type=service.GetConferenceRecordRequest, +): + transport_class = transports.ConferenceRecordsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetConferenceRecord, + "_BaseGetConferenceRecord__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.ConferenceRecord() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.ConferenceRecord.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_conference_record(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_conference_record_rest_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.ConferenceRecord() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "conferenceRecords/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.ConferenceRecord.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_conference_record(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{name=conferenceRecords/*}" % client.transport._host, args[1] + ) + + +def test_get_conference_record_rest_flattened_error(transport: str = "rest"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_conference_record( + service.GetConferenceRecordRequest(), + name="name_value", + ) + + +def test_list_conference_records_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_conference_records + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_conference_records + ] = mock_rpc + + request = {} + client.list_conference_records(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conference_records(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_conference_records_rest_pager(transport: str = "rest"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListConferenceRecordsResponse( + conference_records=[ + resource.ConferenceRecord(), + resource.ConferenceRecord(), + resource.ConferenceRecord(), + ], + next_page_token="abc", + ), + service.ListConferenceRecordsResponse( + conference_records=[], + next_page_token="def", + ), + service.ListConferenceRecordsResponse( + conference_records=[ + resource.ConferenceRecord(), + ], + next_page_token="ghi", + ), + service.ListConferenceRecordsResponse( + conference_records=[ + resource.ConferenceRecord(), + resource.ConferenceRecord(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListConferenceRecordsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_conference_records(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.ConferenceRecord) for i in results) + + pages = list(client.list_conference_records(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_participant_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_participant in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_conference_record] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_participant] = mock_rpc request = {} - client.get_conference_record(request) + client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_conference_record(request) + client.get_participant(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_conference_record_rest_required_fields( - request_type=service.GetConferenceRecordRequest, +def test_get_participant_rest_required_fields( + request_type=service.GetParticipantRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -6291,8 +7412,8 @@ def test_get_conference_record_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetConferenceRecord, - "_BaseGetConferenceRecord__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetParticipant, + "_BaseGetParticipant__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6315,7 +7436,7 @@ def test_get_conference_record_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.ConferenceRecord() + return_value = resource.Participant() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6336,21 +7457,21 @@ def test_get_conference_record_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ConferenceRecord.pb(return_value) + return_value = resource.Participant.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_conference_record(request) + response = client.get_participant(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_conference_record_rest_flattened(): +def test_get_participant_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6359,10 +7480,10 @@ def test_get_conference_record_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ConferenceRecord() + return_value = resource.Participant() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1"} + sample_request = {"name": "conferenceRecords/sample1/participants/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -6374,24 +7495,26 @@ def test_get_conference_record_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ConferenceRecord.pb(return_value) + return_value = resource.Participant.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_conference_record(**mock_args) + client.get_participant(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=conferenceRecords/*}" % client.transport._host, args[1] + "%s/v2beta/{name=conferenceRecords/*/participants/*}" + % client.transport._host, + args[1], ) -def test_get_conference_record_rest_flattened_error(transport: str = "rest"): +def test_get_participant_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6400,13 +7523,13 @@ def test_get_conference_record_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_conference_record( - service.GetConferenceRecordRequest(), + client.get_participant( + service.GetParticipantRequest(), name="name_value", ) -def test_list_conference_records_rest_use_cached_wrapped_rpc(): +def test_list_participants_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6420,34 +7543,173 @@ def test_list_conference_records_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_conference_records - in client._transport._wrapped_methods - ) + assert client._transport.list_participants in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_conference_records - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_participants] = ( + mock_rpc + ) request = {} - client.list_conference_records(request) + client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_conference_records(request) + client.list_participants(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_conference_records_rest_pager(transport: str = "rest"): +def test_list_participants_rest_required_fields( + request_type=service.ListParticipantsRequest, +): + transport_class = transports.ConferenceRecordsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListParticipants, + "_BaseListParticipants__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListParticipantsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListParticipantsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_participants(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_participants_rest_flattened(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListParticipantsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "conferenceRecords/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListParticipantsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_participants(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{parent=conferenceRecords/*}/participants" + % client.transport._host, + args[1], + ) + + +def test_list_participants_rest_flattened_error(transport: str = "rest"): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_participants( + service.ListParticipantsRequest(), + parent="parent_value", + ) + + +def test_list_participants_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6459,28 +7721,28 @@ def test_list_conference_records_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListConferenceRecordsResponse( - conference_records=[ - resource.ConferenceRecord(), - resource.ConferenceRecord(), - resource.ConferenceRecord(), + service.ListParticipantsResponse( + participants=[ + resource.Participant(), + resource.Participant(), + resource.Participant(), ], next_page_token="abc", ), - service.ListConferenceRecordsResponse( - conference_records=[], + service.ListParticipantsResponse( + participants=[], next_page_token="def", ), - service.ListConferenceRecordsResponse( - conference_records=[ - resource.ConferenceRecord(), + service.ListParticipantsResponse( + participants=[ + resource.Participant(), ], next_page_token="ghi", ), - service.ListConferenceRecordsResponse( - conference_records=[ - resource.ConferenceRecord(), - resource.ConferenceRecord(), + service.ListParticipantsResponse( + participants=[ + resource.Participant(), + resource.Participant(), ], ), ) @@ -6488,32 +7750,30 @@ def test_list_conference_records_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - service.ListConferenceRecordsResponse.to_json(x) for x in response - ) + response = tuple(service.ListParticipantsResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {} + sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_conference_records(request=sample_request) + pager = client.list_participants(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.ConferenceRecord) for i in results) + assert all(isinstance(i, resource.Participant) for i in results) - pages = list(client.list_conference_records(request=sample_request).pages) + pages = list(client.list_participants(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_participant_rest_use_cached_wrapped_rpc(): +def test_get_participant_session_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6527,30 +7787,35 @@ def test_get_participant_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_participant in client._transport._wrapped_methods + assert ( + client._transport.get_participant_session + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_participant] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_participant_session + ] = mock_rpc request = {} - client.get_participant(request) + client.get_participant_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_participant(request) + client.get_participant_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_participant_rest_required_fields( - request_type=service.GetParticipantRequest, +def test_get_participant_session_rest_required_fields( + request_type=service.GetParticipantSessionRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -6565,8 +7830,8 @@ def test_get_participant_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetParticipant, - "_BaseGetParticipant__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetParticipantSession, + "_BaseGetParticipantSession__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6589,7 +7854,7 @@ def test_get_participant_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Participant() + return_value = resource.ParticipantSession() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6610,21 +7875,21 @@ def test_get_participant_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Participant.pb(return_value) + return_value = resource.ParticipantSession.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant(request) + response = client.get_participant_session(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_participant_rest_flattened(): +def test_get_participant_session_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6633,10 +7898,12 @@ def test_get_participant_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Participant() + return_value = resource.ParticipantSession() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1/participants/sample2"} + sample_request = { + "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -6648,26 +7915,26 @@ def test_get_participant_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Participant.pb(return_value) + return_value = resource.ParticipantSession.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant(**mock_args) + client.get_participant_session(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=conferenceRecords/*/participants/*}" + "%s/v2beta/{name=conferenceRecords/*/participants/*/participantSessions/*}" % client.transport._host, args[1], ) -def test_get_participant_rest_flattened_error(transport: str = "rest"): +def test_get_participant_session_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6676,13 +7943,13 @@ def test_get_participant_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_participant( - service.GetParticipantRequest(), + client.get_participant_session( + service.GetParticipantSessionRequest(), name="name_value", ) -def test_list_participants_rest_use_cached_wrapped_rpc(): +def test_list_participant_sessions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6696,32 +7963,35 @@ def test_list_participants_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_participants in client._transport._wrapped_methods + assert ( + client._transport.list_participant_sessions + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_participants] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_participant_sessions + ] = mock_rpc request = {} - client.list_participants(request) + client.list_participant_sessions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_participants(request) + client.list_participant_sessions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_participants_rest_required_fields( - request_type=service.ListParticipantsRequest, +def test_list_participant_sessions_rest_required_fields( + request_type=service.ListParticipantSessionsRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -6736,8 +8006,8 @@ def test_list_participants_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListParticipants, - "_BaseListParticipants__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListParticipantSessions, + "_BaseListParticipantSessions__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6769,7 +8039,7 @@ def test_list_participants_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListParticipantsResponse() + return_value = service.ListParticipantSessionsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6790,21 +8060,21 @@ def test_list_participants_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantsResponse.pb(return_value) + return_value = service.ListParticipantSessionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participants(request) + response = client.list_participant_sessions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_participants_rest_flattened(): +def test_list_participant_sessions_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6813,10 +8083,10 @@ def test_list_participants_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantsResponse() + return_value = service.ListParticipantSessionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -6828,26 +8098,26 @@ def test_list_participants_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantsResponse.pb(return_value) + return_value = service.ListParticipantSessionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participants(**mock_args) + client.list_participant_sessions(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{parent=conferenceRecords/*}/participants" + "%s/v2beta/{parent=conferenceRecords/*/participants/*}/participantSessions" % client.transport._host, args[1], ) -def test_list_participants_rest_flattened_error(transport: str = "rest"): +def test_list_participant_sessions_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6856,13 +8126,13 @@ def test_list_participants_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_participants( - service.ListParticipantsRequest(), + client.list_participant_sessions( + service.ListParticipantSessionsRequest(), parent="parent_value", ) -def test_list_participants_rest_pager(transport: str = "rest"): +def test_list_participant_sessions_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6874,28 +8144,28 @@ def test_list_participants_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListParticipantsResponse( - participants=[ - resource.Participant(), - resource.Participant(), - resource.Participant(), + service.ListParticipantSessionsResponse( + participant_sessions=[ + resource.ParticipantSession(), + resource.ParticipantSession(), + resource.ParticipantSession(), ], next_page_token="abc", ), - service.ListParticipantsResponse( - participants=[], + service.ListParticipantSessionsResponse( + participant_sessions=[], next_page_token="def", ), - service.ListParticipantsResponse( - participants=[ - resource.Participant(), + service.ListParticipantSessionsResponse( + participant_sessions=[ + resource.ParticipantSession(), ], next_page_token="ghi", ), - service.ListParticipantsResponse( - participants=[ - resource.Participant(), - resource.Participant(), + service.ListParticipantSessionsResponse( + participant_sessions=[ + resource.ParticipantSession(), + resource.ParticipantSession(), ], ), ) @@ -6903,30 +8173,32 @@ def test_list_participants_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListParticipantsResponse.to_json(x) for x in response) + response = tuple( + service.ListParticipantSessionsResponse.to_json(x) for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} - pager = client.list_participants(request=sample_request) + pager = client.list_participant_sessions(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.Participant) for i in results) + assert all(isinstance(i, resource.ParticipantSession) for i in results) - pages = list(client.list_participants(request=sample_request).pages) + pages = list(client.list_participant_sessions(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_participant_session_rest_use_cached_wrapped_rpc(): +def test_get_recording_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6940,36 +8212,29 @@ def test_get_participant_session_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_participant_session - in client._transport._wrapped_methods - ) + assert client._transport.get_recording in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_participant_session - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_recording] = mock_rpc request = {} - client.get_participant_session(request) + client.get_recording(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_participant_session(request) + client.get_recording(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_participant_session_rest_required_fields( - request_type=service.GetParticipantSessionRequest, -): +def test_get_recording_rest_required_fields(request_type=service.GetRecordingRequest): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -6983,8 +8248,8 @@ def test_get_participant_session_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetParticipantSession, - "_BaseGetParticipantSession__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetRecording, + "_BaseGetRecording__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7007,7 +8272,7 @@ def test_get_participant_session_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.ParticipantSession() + return_value = resource.Recording() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7028,21 +8293,21 @@ def test_get_participant_session_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ParticipantSession.pb(return_value) + return_value = resource.Recording.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant_session(request) + response = client.get_recording(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_participant_session_rest_flattened(): +def test_get_recording_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7051,12 +8316,10 @@ def test_get_participant_session_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ParticipantSession() + return_value = resource.Recording() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" - } + sample_request = {"name": "conferenceRecords/sample1/recordings/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -7068,26 +8331,26 @@ def test_get_participant_session_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ParticipantSession.pb(return_value) + return_value = resource.Recording.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant_session(**mock_args) + client.get_recording(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=conferenceRecords/*/participants/*/participantSessions/*}" + "%s/v2beta/{name=conferenceRecords/*/recordings/*}" % client.transport._host, args[1], ) -def test_get_participant_session_rest_flattened_error(transport: str = "rest"): +def test_get_recording_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7096,13 +8359,13 @@ def test_get_participant_session_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_participant_session( - service.GetParticipantSessionRequest(), + client.get_recording( + service.GetRecordingRequest(), name="name_value", ) -def test_list_participant_sessions_rest_use_cached_wrapped_rpc(): +def test_list_recordings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7116,35 +8379,30 @@ def test_list_participant_sessions_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_participant_sessions - in client._transport._wrapped_methods - ) + assert client._transport.list_recordings in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_participant_sessions - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_recordings] = mock_rpc request = {} - client.list_participant_sessions(request) + client.list_recordings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_participant_sessions(request) + client.list_recordings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_participant_sessions_rest_required_fields( - request_type=service.ListParticipantSessionsRequest, +def test_list_recordings_rest_required_fields( + request_type=service.ListRecordingsRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -7159,8 +8417,8 @@ def test_list_participant_sessions_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListParticipantSessions, - "_BaseListParticipantSessions__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListRecordings, + "_BaseListRecordings__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7175,7 +8433,6 @@ def test_list_participant_sessions_rest_required_fields( # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", "pageSize", "pageToken", ) @@ -7192,7 +8449,7 @@ def test_list_participant_sessions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListParticipantSessionsResponse() + return_value = service.ListRecordingsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7213,21 +8470,21 @@ def test_list_participant_sessions_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantSessionsResponse.pb(return_value) + return_value = service.ListRecordingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participant_sessions(request) + response = client.list_recordings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_participant_sessions_rest_flattened(): +def test_list_recordings_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7236,10 +8493,10 @@ def test_list_participant_sessions_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantSessionsResponse() + return_value = service.ListRecordingsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -7251,26 +8508,26 @@ def test_list_participant_sessions_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantSessionsResponse.pb(return_value) + return_value = service.ListRecordingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participant_sessions(**mock_args) + client.list_recordings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{parent=conferenceRecords/*/participants/*}/participantSessions" + "%s/v2beta/{parent=conferenceRecords/*}/recordings" % client.transport._host, args[1], ) -def test_list_participant_sessions_rest_flattened_error(transport: str = "rest"): +def test_list_recordings_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7279,13 +8536,13 @@ def test_list_participant_sessions_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_participant_sessions( - service.ListParticipantSessionsRequest(), + client.list_recordings( + service.ListRecordingsRequest(), parent="parent_value", ) -def test_list_participant_sessions_rest_pager(transport: str = "rest"): +def test_list_recordings_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7297,28 +8554,28 @@ def test_list_participant_sessions_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListParticipantSessionsResponse( - participant_sessions=[ - resource.ParticipantSession(), - resource.ParticipantSession(), - resource.ParticipantSession(), + service.ListRecordingsResponse( + recordings=[ + resource.Recording(), + resource.Recording(), + resource.Recording(), ], next_page_token="abc", ), - service.ListParticipantSessionsResponse( - participant_sessions=[], + service.ListRecordingsResponse( + recordings=[], next_page_token="def", ), - service.ListParticipantSessionsResponse( - participant_sessions=[ - resource.ParticipantSession(), + service.ListRecordingsResponse( + recordings=[ + resource.Recording(), ], next_page_token="ghi", ), - service.ListParticipantSessionsResponse( - participant_sessions=[ - resource.ParticipantSession(), - resource.ParticipantSession(), + service.ListRecordingsResponse( + recordings=[ + resource.Recording(), + resource.Recording(), ], ), ) @@ -7326,32 +8583,30 @@ def test_list_participant_sessions_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - service.ListParticipantSessionsResponse.to_json(x) for x in response - ) + response = tuple(service.ListRecordingsResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1/participants/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_participant_sessions(request=sample_request) + pager = client.list_recordings(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.ParticipantSession) for i in results) + assert all(isinstance(i, resource.Recording) for i in results) - pages = list(client.list_participant_sessions(request=sample_request).pages) + pages = list(client.list_recordings(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_recording_rest_use_cached_wrapped_rpc(): +def test_get_transcript_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7365,29 +8620,29 @@ def test_get_recording_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_recording in client._transport._wrapped_methods + assert client._transport.get_transcript in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_recording] = mock_rpc + client._transport._wrapped_methods[client._transport.get_transcript] = mock_rpc request = {} - client.get_recording(request) + client.get_transcript(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_recording(request) + client.get_transcript(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_recording_rest_required_fields(request_type=service.GetRecordingRequest): +def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptRequest): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -7401,8 +8656,8 @@ def test_get_recording_rest_required_fields(request_type=service.GetRecordingReq # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetRecording, - "_BaseGetRecording__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetTranscript, + "_BaseGetTranscript__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7425,7 +8680,7 @@ def test_get_recording_rest_required_fields(request_type=service.GetRecordingReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Recording() + return_value = resource.Transcript() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7446,21 +8701,21 @@ def test_get_recording_rest_required_fields(request_type=service.GetRecordingReq response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Recording.pb(return_value) + return_value = resource.Transcript.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_recording(request) + response = client.get_transcript(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_recording_rest_flattened(): +def test_get_transcript_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7469,10 +8724,10 @@ def test_get_recording_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Recording() + return_value = resource.Transcript() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1/recordings/sample2"} + sample_request = {"name": "conferenceRecords/sample1/transcripts/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -7484,26 +8739,26 @@ def test_get_recording_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Recording.pb(return_value) + return_value = resource.Transcript.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_recording(**mock_args) + client.get_transcript(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=conferenceRecords/*/recordings/*}" + "%s/v2beta/{name=conferenceRecords/*/transcripts/*}" % client.transport._host, args[1], ) -def test_get_recording_rest_flattened_error(transport: str = "rest"): +def test_get_transcript_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7512,13 +8767,13 @@ def test_get_recording_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_recording( - service.GetRecordingRequest(), + client.get_transcript( + service.GetTranscriptRequest(), name="name_value", ) -def test_list_recordings_rest_use_cached_wrapped_rpc(): +def test_list_transcripts_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7532,30 +8787,32 @@ def test_list_recordings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_recordings in client._transport._wrapped_methods + assert client._transport.list_transcripts in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_recordings] = mock_rpc + client._transport._wrapped_methods[client._transport.list_transcripts] = ( + mock_rpc + ) request = {} - client.list_recordings(request) + client.list_transcripts(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_recordings(request) + client.list_transcripts(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_recordings_rest_required_fields( - request_type=service.ListRecordingsRequest, +def test_list_transcripts_rest_required_fields( + request_type=service.ListTranscriptsRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -7570,8 +8827,8 @@ def test_list_recordings_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListRecordings, - "_BaseListRecordings__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListTranscripts, + "_BaseListTranscripts__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7602,7 +8859,7 @@ def test_list_recordings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListRecordingsResponse() + return_value = service.ListTranscriptsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7623,21 +8880,21 @@ def test_list_recordings_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRecordingsResponse.pb(return_value) + return_value = service.ListTranscriptsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_recordings(request) + response = client.list_transcripts(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_recordings_rest_flattened(): +def test_list_transcripts_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7646,7 +8903,7 @@ def test_list_recordings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListRecordingsResponse() + return_value = service.ListTranscriptsResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "conferenceRecords/sample1"} @@ -7661,26 +8918,26 @@ def test_list_recordings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRecordingsResponse.pb(return_value) + return_value = service.ListTranscriptsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_recordings(**mock_args) + client.list_transcripts(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{parent=conferenceRecords/*}/recordings" + "%s/v2beta/{parent=conferenceRecords/*}/transcripts" % client.transport._host, args[1], ) -def test_list_recordings_rest_flattened_error(transport: str = "rest"): +def test_list_transcripts_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7689,13 +8946,13 @@ def test_list_recordings_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_recordings( - service.ListRecordingsRequest(), + client.list_transcripts( + service.ListTranscriptsRequest(), parent="parent_value", ) -def test_list_recordings_rest_pager(transport: str = "rest"): +def test_list_transcripts_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7707,28 +8964,28 @@ def test_list_recordings_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListRecordingsResponse( - recordings=[ - resource.Recording(), - resource.Recording(), - resource.Recording(), + service.ListTranscriptsResponse( + transcripts=[ + resource.Transcript(), + resource.Transcript(), + resource.Transcript(), ], next_page_token="abc", ), - service.ListRecordingsResponse( - recordings=[], + service.ListTranscriptsResponse( + transcripts=[], next_page_token="def", ), - service.ListRecordingsResponse( - recordings=[ - resource.Recording(), + service.ListTranscriptsResponse( + transcripts=[ + resource.Transcript(), ], next_page_token="ghi", ), - service.ListRecordingsResponse( - recordings=[ - resource.Recording(), - resource.Recording(), + service.ListTranscriptsResponse( + transcripts=[ + resource.Transcript(), + resource.Transcript(), ], ), ) @@ -7736,7 +8993,7 @@ def test_list_recordings_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListRecordingsResponse.to_json(x) for x in response) + response = tuple(service.ListTranscriptsResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") @@ -7745,21 +9002,21 @@ def test_list_recordings_rest_pager(transport: str = "rest"): sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_recordings(request=sample_request) + pager = client.list_transcripts(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.Recording) for i in results) + assert all(isinstance(i, resource.Transcript) for i in results) - pages = list(client.list_recordings(request=sample_request).pages) + pages = list(client.list_transcripts(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_transcript_rest_use_cached_wrapped_rpc(): +def test_get_transcript_entry_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7773,29 +9030,35 @@ def test_get_transcript_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_transcript in client._transport._wrapped_methods + assert ( + client._transport.get_transcript_entry in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_transcript] = mock_rpc + client._transport._wrapped_methods[client._transport.get_transcript_entry] = ( + mock_rpc + ) request = {} - client.get_transcript(request) + client.get_transcript_entry(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_transcript(request) + client.get_transcript_entry(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptRequest): +def test_get_transcript_entry_rest_required_fields( + request_type=service.GetTranscriptEntryRequest, +): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -7809,8 +9072,8 @@ def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptR # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetTranscript, - "_BaseGetTranscript__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetTranscriptEntry, + "_BaseGetTranscriptEntry__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7833,7 +9096,7 @@ def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Transcript() + return_value = resource.TranscriptEntry() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7854,21 +9117,21 @@ def test_get_transcript_rest_required_fields(request_type=service.GetTranscriptR response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Transcript.pb(return_value) + return_value = resource.TranscriptEntry.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript(request) + response = client.get_transcript_entry(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_transcript_rest_flattened(): +def test_get_transcript_entry_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7877,10 +9140,12 @@ def test_get_transcript_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Transcript() + return_value = resource.TranscriptEntry() # get arguments that satisfy an http rule for this method - sample_request = {"name": "conferenceRecords/sample1/transcripts/sample2"} + sample_request = { + "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -7892,26 +9157,26 @@ def test_get_transcript_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Transcript.pb(return_value) + return_value = resource.TranscriptEntry.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript(**mock_args) + client.get_transcript_entry(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=conferenceRecords/*/transcripts/*}" + "%s/v2beta/{name=conferenceRecords/*/transcripts/*/entries/*}" % client.transport._host, args[1], ) -def test_get_transcript_rest_flattened_error(transport: str = "rest"): +def test_get_transcript_entry_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7920,13 +9185,13 @@ def test_get_transcript_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_transcript( - service.GetTranscriptRequest(), + client.get_transcript_entry( + service.GetTranscriptEntryRequest(), name="name_value", ) -def test_list_transcripts_rest_use_cached_wrapped_rpc(): +def test_list_transcript_entries_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7940,32 +9205,35 @@ def test_list_transcripts_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_transcripts in client._transport._wrapped_methods + assert ( + client._transport.list_transcript_entries + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_transcripts] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_transcript_entries + ] = mock_rpc request = {} - client.list_transcripts(request) + client.list_transcript_entries(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_transcripts(request) + client.list_transcript_entries(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_transcripts_rest_required_fields( - request_type=service.ListTranscriptsRequest, +def test_list_transcript_entries_rest_required_fields( + request_type=service.ListTranscriptEntriesRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -7980,8 +9248,8 @@ def test_list_transcripts_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListTranscripts, - "_BaseListTranscripts__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListTranscriptEntries, + "_BaseListTranscriptEntries__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -8012,7 +9280,7 @@ def test_list_transcripts_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptsResponse() + return_value = service.ListTranscriptEntriesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8033,21 +9301,21 @@ def test_list_transcripts_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptsResponse.pb(return_value) + return_value = service.ListTranscriptEntriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcripts(request) + response = client.list_transcript_entries(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_transcripts_rest_flattened(): +def test_list_transcript_entries_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8056,10 +9324,10 @@ def test_list_transcripts_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptsResponse() + return_value = service.ListTranscriptEntriesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -8071,26 +9339,26 @@ def test_list_transcripts_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptsResponse.pb(return_value) + return_value = service.ListTranscriptEntriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcripts(**mock_args) + client.list_transcript_entries(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{parent=conferenceRecords/*}/transcripts" + "%s/v2beta/{parent=conferenceRecords/*/transcripts/*}/entries" % client.transport._host, args[1], ) -def test_list_transcripts_rest_flattened_error(transport: str = "rest"): +def test_list_transcript_entries_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8099,13 +9367,13 @@ def test_list_transcripts_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_transcripts( - service.ListTranscriptsRequest(), + client.list_transcript_entries( + service.ListTranscriptEntriesRequest(), parent="parent_value", ) -def test_list_transcripts_rest_pager(transport: str = "rest"): +def test_list_transcript_entries_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8115,30 +9383,30 @@ def test_list_transcripts_rest_pager(transport: str = "rest"): with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListTranscriptsResponse( - transcripts=[ - resource.Transcript(), - resource.Transcript(), - resource.Transcript(), + # Set the response as a series of pages + response = ( + service.ListTranscriptEntriesResponse( + transcript_entries=[ + resource.TranscriptEntry(), + resource.TranscriptEntry(), + resource.TranscriptEntry(), ], next_page_token="abc", ), - service.ListTranscriptsResponse( - transcripts=[], + service.ListTranscriptEntriesResponse( + transcript_entries=[], next_page_token="def", ), - service.ListTranscriptsResponse( - transcripts=[ - resource.Transcript(), + service.ListTranscriptEntriesResponse( + transcript_entries=[ + resource.TranscriptEntry(), ], next_page_token="ghi", ), - service.ListTranscriptsResponse( - transcripts=[ - resource.Transcript(), - resource.Transcript(), + service.ListTranscriptEntriesResponse( + transcript_entries=[ + resource.TranscriptEntry(), + resource.TranscriptEntry(), ], ), ) @@ -8146,30 +9414,32 @@ def test_list_transcripts_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListTranscriptsResponse.to_json(x) for x in response) + response = tuple( + service.ListTranscriptEntriesResponse.to_json(x) for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1"} + sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} - pager = client.list_transcripts(request=sample_request) + pager = client.list_transcript_entries(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.Transcript) for i in results) + assert all(isinstance(i, resource.TranscriptEntry) for i in results) - pages = list(client.list_transcripts(request=sample_request).pages) + pages = list(client.list_transcript_entries(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_transcript_entry_rest_use_cached_wrapped_rpc(): +def test_get_smart_note_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8183,35 +9453,29 @@ def test_get_transcript_entry_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_transcript_entry in client._transport._wrapped_methods - ) + assert client._transport.get_smart_note in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_transcript_entry] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_smart_note] = mock_rpc request = {} - client.get_transcript_entry(request) + client.get_smart_note(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_transcript_entry(request) + client.get_smart_note(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_transcript_entry_rest_required_fields( - request_type=service.GetTranscriptEntryRequest, -): +def test_get_smart_note_rest_required_fields(request_type=service.GetSmartNoteRequest): transport_class = transports.ConferenceRecordsServiceRestTransport request_init = {} @@ -8225,8 +9489,8 @@ def test_get_transcript_entry_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetTranscriptEntry, - "_BaseGetTranscriptEntry__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetSmartNote, + "_BaseGetSmartNote__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -8249,7 +9513,7 @@ def test_get_transcript_entry_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.TranscriptEntry() + return_value = resource.SmartNote() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8270,21 +9534,21 @@ def test_get_transcript_entry_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.TranscriptEntry.pb(return_value) + return_value = resource.SmartNote.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript_entry(request) + response = client.get_smart_note(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_transcript_entry_rest_flattened(): +def test_get_smart_note_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8293,12 +9557,10 @@ def test_get_transcript_entry_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.TranscriptEntry() + return_value = resource.SmartNote() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" - } + sample_request = {"name": "conferenceRecords/sample1/smartNotes/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -8310,26 +9572,26 @@ def test_get_transcript_entry_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.TranscriptEntry.pb(return_value) + return_value = resource.SmartNote.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript_entry(**mock_args) + client.get_smart_note(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=conferenceRecords/*/transcripts/*/entries/*}" + "%s/v2beta/{name=conferenceRecords/*/smartNotes/*}" % client.transport._host, args[1], ) -def test_get_transcript_entry_rest_flattened_error(transport: str = "rest"): +def test_get_smart_note_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8338,13 +9600,13 @@ def test_get_transcript_entry_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_transcript_entry( - service.GetTranscriptEntryRequest(), + client.get_smart_note( + service.GetSmartNoteRequest(), name="name_value", ) -def test_list_transcript_entries_rest_use_cached_wrapped_rpc(): +def test_list_smart_notes_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8358,35 +9620,32 @@ def test_list_transcript_entries_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_transcript_entries - in client._transport._wrapped_methods - ) + assert client._transport.list_smart_notes in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_transcript_entries - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_smart_notes] = ( + mock_rpc + ) request = {} - client.list_transcript_entries(request) + client.list_smart_notes(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_transcript_entries(request) + client.list_smart_notes(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_transcript_entries_rest_required_fields( - request_type=service.ListTranscriptEntriesRequest, +def test_list_smart_notes_rest_required_fields( + request_type=service.ListSmartNotesRequest, ): transport_class = transports.ConferenceRecordsServiceRestTransport @@ -8401,8 +9660,8 @@ def test_list_transcript_entries_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListTranscriptEntries, - "_BaseListTranscriptEntries__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListSmartNotes, + "_BaseListSmartNotes__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -8433,7 +9692,7 @@ def test_list_transcript_entries_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptEntriesResponse() + return_value = service.ListSmartNotesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8454,21 +9713,21 @@ def test_list_transcript_entries_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptEntriesResponse.pb(return_value) + return_value = service.ListSmartNotesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcript_entries(request) + response = client.list_smart_notes(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_transcript_entries_rest_flattened(): +def test_list_smart_notes_rest_flattened(): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8477,10 +9736,10 @@ def test_list_transcript_entries_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptEntriesResponse() + return_value = service.ListSmartNotesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -8492,26 +9751,26 @@ def test_list_transcript_entries_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptEntriesResponse.pb(return_value) + return_value = service.ListSmartNotesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcript_entries(**mock_args) + client.list_smart_notes(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{parent=conferenceRecords/*/transcripts/*}/entries" + "%s/v2beta/{parent=conferenceRecords/*}/smartNotes" % client.transport._host, args[1], ) -def test_list_transcript_entries_rest_flattened_error(transport: str = "rest"): +def test_list_smart_notes_rest_flattened_error(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8520,13 +9779,13 @@ def test_list_transcript_entries_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_transcript_entries( - service.ListTranscriptEntriesRequest(), + client.list_smart_notes( + service.ListSmartNotesRequest(), parent="parent_value", ) -def test_list_transcript_entries_rest_pager(transport: str = "rest"): +def test_list_smart_notes_rest_pager(transport: str = "rest"): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8538,28 +9797,28 @@ def test_list_transcript_entries_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListTranscriptEntriesResponse( - transcript_entries=[ - resource.TranscriptEntry(), - resource.TranscriptEntry(), - resource.TranscriptEntry(), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), + resource.SmartNote(), ], next_page_token="abc", ), - service.ListTranscriptEntriesResponse( - transcript_entries=[], + service.ListSmartNotesResponse( + smart_notes=[], next_page_token="def", ), - service.ListTranscriptEntriesResponse( - transcript_entries=[ - resource.TranscriptEntry(), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), ], next_page_token="ghi", ), - service.ListTranscriptEntriesResponse( - transcript_entries=[ - resource.TranscriptEntry(), - resource.TranscriptEntry(), + service.ListSmartNotesResponse( + smart_notes=[ + resource.SmartNote(), + resource.SmartNote(), ], ), ) @@ -8567,27 +9826,25 @@ def test_list_transcript_entries_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - service.ListTranscriptEntriesResponse.to_json(x) for x in response - ) + response = tuple(service.ListSmartNotesResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + sample_request = {"parent": "conferenceRecords/sample1"} - pager = client.list_transcript_entries(request=sample_request) + pager = client.list_smart_notes(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resource.TranscriptEntry) for i in results) + assert all(isinstance(i, resource.SmartNote) for i in results) - pages = list(client.list_transcript_entries(request=sample_request).pages) + pages = list(client.list_smart_notes(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -8952,6 +10209,46 @@ def test_list_transcript_entries_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_smart_note_empty_call_grpc(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + call.return_value = resource.SmartNote() + client.get_smart_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSmartNoteRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_smart_notes_empty_call_grpc(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + call.return_value = service.ListSmartNotesResponse() + client.list_smart_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = ConferenceRecordsServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -9064,256 +10361,580 @@ async def test_list_participants_empty_call_grpc_asyncio(): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListParticipantsResponse( + service.ListParticipantsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.list_participants(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListParticipantsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_participant_session_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_participant_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.ParticipantSession( + name="name_value", + ) + ) + await client.get_participant_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetParticipantSessionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_participant_sessions_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_participant_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListParticipantSessionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_participant_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListParticipantSessionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_recording_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_recording), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Recording( + name="name_value", + state=resource.Recording.State.STARTED, + ) + ) + await client.get_recording(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetRecordingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_recordings_empty_call_grpc_asyncio(): + client = ConferenceRecordsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_recordings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListRecordingsResponse( next_page_token="next_page_token_value", - total_size=1086, ) ) - await client.list_participants(request=None) + await client.list_recordings(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListParticipantsRequest() + request_msg = service.ListRecordingsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_participant_session_empty_call_grpc_asyncio(): +async def test_get_transcript_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_participant_session), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_transcript), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.ParticipantSession( + resource.Transcript( name="name_value", + state=resource.Transcript.State.STARTED, ) ) - await client.get_participant_session(request=None) + await client.get_transcript(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetParticipantSessionRequest() + request_msg = service.GetTranscriptRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_participant_sessions_empty_call_grpc_asyncio(): +async def test_list_transcripts_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_participant_sessions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_transcripts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListParticipantSessionsResponse( + service.ListTranscriptsResponse( next_page_token="next_page_token_value", ) ) - await client.list_participant_sessions(request=None) + await client.list_transcripts(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListParticipantSessionsRequest() + request_msg = service.ListTranscriptsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_recording_empty_call_grpc_asyncio(): +async def test_get_transcript_entry_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_recording), "__call__") as call: + with mock.patch.object( + type(client.transport.get_transcript_entry), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.Recording( + resource.TranscriptEntry( name="name_value", - state=resource.Recording.State.STARTED, + participant="participant_value", + text="text_value", + language_code="language_code_value", ) ) - await client.get_recording(request=None) + await client.get_transcript_entry(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetRecordingRequest() + request_msg = service.GetTranscriptEntryRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_recordings_empty_call_grpc_asyncio(): +async def test_list_transcript_entries_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_recordings), "__call__") as call: + with mock.patch.object( + type(client.transport.list_transcript_entries), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListRecordingsResponse( + service.ListTranscriptEntriesResponse( next_page_token="next_page_token_value", ) ) - await client.list_recordings(request=None) + await client.list_transcript_entries(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListRecordingsRequest() + request_msg = service.ListTranscriptEntriesRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_transcript_empty_call_grpc_asyncio(): +async def test_get_smart_note_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_transcript), "__call__") as call: + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.Transcript( + resource.SmartNote( name="name_value", - state=resource.Transcript.State.STARTED, + state=resource.SmartNote.State.STARTED, ) ) - await client.get_transcript(request=None) + await client.get_smart_note(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetTranscriptRequest() + request_msg = service.GetSmartNoteRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_transcripts_empty_call_grpc_asyncio(): +async def test_list_smart_notes_empty_call_grpc_asyncio(): client = ConferenceRecordsServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_transcripts), "__call__") as call: + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListTranscriptsResponse( + service.ListSmartNotesResponse( next_page_token="next_page_token_value", ) ) - await client.list_transcripts(request=None) + await client.list_smart_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ConferenceRecordsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_conference_record_rest_bad_request( + request_type=service.GetConferenceRecordRequest, +): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "conferenceRecords/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_conference_record(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetConferenceRecordRequest, + dict, + ], +) +def test_get_conference_record_rest_call_success(request_type): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "conferenceRecords/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.ConferenceRecord( + name="name_value", + space="space_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.ConferenceRecord.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_conference_record(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.ConferenceRecord) + assert response.name == "name_value" + assert response.space == "space_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conference_record_rest_interceptors(null_interceptor): + transport = transports.ConferenceRecordsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ConferenceRecordsServiceRestInterceptor(), + ) + client = ConferenceRecordsServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_conference_record", + ) as post, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_conference_record_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "pre_get_conference_record", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetConferenceRecordRequest.pb( + service.GetConferenceRecordRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.ConferenceRecord.to_json(resource.ConferenceRecord()) + req.return_value.content = return_value + + request = service.GetConferenceRecordRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.ConferenceRecord() + post_with_metadata.return_value = resource.ConferenceRecord(), metadata + + client.get_conference_record( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_conference_records_rest_bad_request( + request_type=service.ListConferenceRecordsRequest, +): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_conference_records(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListConferenceRecordsRequest, + dict, + ], +) +def test_list_conference_records_rest_call_success(request_type): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListTranscriptsRequest() - assert args[0] == request_msg + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListConferenceRecordsResponse( + next_page_token="next_page_token_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_transcript_entry_empty_call_grpc_asyncio(): - client = ConferenceRecordsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_transcript_entry), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource.TranscriptEntry( - name="name_value", - participant="participant_value", - text="text_value", - language_code="language_code_value", - ) - ) - await client.get_transcript_entry(request=None) + # Convert return value to protobuf type + return_value = service.ListConferenceRecordsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_conference_records(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetTranscriptEntryRequest() - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConferenceRecordsPager) + assert response.next_page_token == "next_page_token_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_transcript_entries_empty_call_grpc_asyncio(): - client = ConferenceRecordsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conference_records_rest_interceptors(null_interceptor): + transport = transports.ConferenceRecordsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ConferenceRecordsServiceRestInterceptor(), ) + client = ConferenceRecordsServiceClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_transcript_entries), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListTranscriptEntriesResponse( - next_page_token="next_page_token_value", - ) + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_conference_records", + ) as post, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_conference_records_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ConferenceRecordsServiceRestInterceptor, + "pre_list_conference_records", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListConferenceRecordsRequest.pb( + service.ListConferenceRecordsRequest() ) - await client.list_transcript_entries(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListTranscriptEntriesRequest() - assert args[0] == request_msg + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListConferenceRecordsResponse.to_json( + service.ListConferenceRecordsResponse() + ) + req.return_value.content = return_value + + request = service.ListConferenceRecordsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListConferenceRecordsResponse() + post_with_metadata.return_value = ( + service.ListConferenceRecordsResponse(), + metadata, + ) + client.list_conference_records( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = ConferenceRecordsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_conference_record_rest_bad_request( - request_type=service.GetConferenceRecordRequest, -): +def test_get_participant_rest_bad_request(request_type=service.GetParticipantRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1"} + request_init = {"name": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9329,31 +10950,30 @@ def test_get_conference_record_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_conference_record(request) + client.get_participant(request) @pytest.mark.parametrize( "request_type", [ - service.GetConferenceRecordRequest, + service.GetParticipantRequest, dict, ], ) -def test_get_conference_record_rest_call_success(request_type): +def test_get_participant_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1"} + request_init = {"name": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ConferenceRecord( + return_value = resource.Participant( name="name_value", - space="space_value", ) # Wrap the value into a proper Response obj @@ -9361,21 +10981,20 @@ def test_get_conference_record_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ConferenceRecord.pb(return_value) + return_value = resource.Participant.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_conference_record(request) + response = client.get_participant(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.ConferenceRecord) + assert isinstance(response, resource.Participant) assert response.name == "name_value" - assert response.space == "space_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conference_record_rest_interceptors(null_interceptor): +def test_get_participant_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9388,24 +11007,20 @@ def test_get_conference_record_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_get_conference_record", + transports.ConferenceRecordsServiceRestInterceptor, "post_get_participant" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_conference_record_with_metadata", + "post_get_participant_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_get_conference_record", + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_participant" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetConferenceRecordRequest.pb( - service.GetConferenceRecordRequest() - ) + pb_message = service.GetParticipantRequest.pb(service.GetParticipantRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9416,19 +11031,19 @@ def test_get_conference_record_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.ConferenceRecord.to_json(resource.ConferenceRecord()) + return_value = resource.Participant.to_json(resource.Participant()) req.return_value.content = return_value - request = service.GetConferenceRecordRequest() + request = service.GetParticipantRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.ConferenceRecord() - post_with_metadata.return_value = resource.ConferenceRecord(), metadata + post.return_value = resource.Participant() + post_with_metadata.return_value = resource.Participant(), metadata - client.get_conference_record( + client.get_participant( request, metadata=[ ("key", "val"), @@ -9441,14 +11056,14 @@ def test_get_conference_record_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_conference_records_rest_bad_request( - request_type=service.ListConferenceRecordsRequest, +def test_list_participants_rest_bad_request( + request_type=service.ListParticipantsRequest, ): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9464,30 +11079,31 @@ def test_list_conference_records_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_conference_records(request) + client.list_participants(request) @pytest.mark.parametrize( "request_type", [ - service.ListConferenceRecordsRequest, + service.ListParticipantsRequest, dict, ], ) -def test_list_conference_records_rest_call_success(request_type): +def test_list_participants_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListConferenceRecordsResponse( + return_value = service.ListParticipantsResponse( next_page_token="next_page_token_value", + total_size=1086, ) # Wrap the value into a proper Response obj @@ -9495,20 +11111,21 @@ def test_list_conference_records_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListConferenceRecordsResponse.pb(return_value) + return_value = service.ListParticipantsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_conference_records(request) + response = client.list_participants(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConferenceRecordsPager) + assert isinstance(response, pagers.ListParticipantsPager) assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conference_records_rest_interceptors(null_interceptor): +def test_list_participants_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9521,23 +11138,21 @@ def test_list_conference_records_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_list_conference_records", + transports.ConferenceRecordsServiceRestInterceptor, "post_list_participants" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_conference_records_with_metadata", + "post_list_participants_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_list_conference_records", + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_participants" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListConferenceRecordsRequest.pb( - service.ListConferenceRecordsRequest() + pb_message = service.ListParticipantsRequest.pb( + service.ListParticipantsRequest() ) transcode.return_value = { "method": "post", @@ -9549,24 +11164,21 @@ def test_list_conference_records_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListConferenceRecordsResponse.to_json( - service.ListConferenceRecordsResponse() + return_value = service.ListParticipantsResponse.to_json( + service.ListParticipantsResponse() ) req.return_value.content = return_value - request = service.ListConferenceRecordsRequest() + request = service.ListParticipantsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListConferenceRecordsResponse() - post_with_metadata.return_value = ( - service.ListConferenceRecordsResponse(), - metadata, - ) + post.return_value = service.ListParticipantsResponse() + post_with_metadata.return_value = service.ListParticipantsResponse(), metadata - client.list_conference_records( + client.list_participants( request, metadata=[ ("key", "val"), @@ -9579,12 +11191,16 @@ def test_list_conference_records_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_participant_rest_bad_request(request_type=service.GetParticipantRequest): +def test_get_participant_session_rest_bad_request( + request_type=service.GetParticipantSessionRequest, +): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/participants/sample2"} + request_init = { + "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9600,29 +11216,31 @@ def test_get_participant_rest_bad_request(request_type=service.GetParticipantReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant(request) + client.get_participant_session(request) @pytest.mark.parametrize( "request_type", [ - service.GetParticipantRequest, + service.GetParticipantSessionRequest, dict, ], ) -def test_get_participant_rest_call_success(request_type): +def test_get_participant_session_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/participants/sample2"} + request_init = { + "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Participant( + return_value = resource.ParticipantSession( name="name_value", ) @@ -9631,20 +11249,20 @@ def test_get_participant_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Participant.pb(return_value) + return_value = resource.ParticipantSession.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant(request) + response = client.get_participant_session(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Participant) + assert isinstance(response, resource.ParticipantSession) assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_participant_rest_interceptors(null_interceptor): +def test_get_participant_session_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9657,20 +11275,24 @@ def test_get_participant_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_get_participant" + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_participant_session", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_participant_with_metadata", + "post_get_participant_session_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_get_participant" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_get_participant_session", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetParticipantRequest.pb(service.GetParticipantRequest()) + pb_message = service.GetParticipantSessionRequest.pb( + service.GetParticipantSessionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9681,19 +11303,21 @@ def test_get_participant_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Participant.to_json(resource.Participant()) + return_value = resource.ParticipantSession.to_json( + resource.ParticipantSession() + ) req.return_value.content = return_value - request = service.GetParticipantRequest() + request = service.GetParticipantSessionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Participant() - post_with_metadata.return_value = resource.Participant(), metadata + post.return_value = resource.ParticipantSession() + post_with_metadata.return_value = resource.ParticipantSession(), metadata - client.get_participant( + client.get_participant_session( request, metadata=[ ("key", "val"), @@ -9706,14 +11330,14 @@ def test_get_participant_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_participants_rest_bad_request( - request_type=service.ListParticipantsRequest, +def test_list_participant_sessions_rest_bad_request( + request_type=service.ListParticipantSessionsRequest, ): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9729,31 +11353,30 @@ def test_list_participants_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participants(request) + client.list_participant_sessions(request) @pytest.mark.parametrize( "request_type", [ - service.ListParticipantsRequest, + service.ListParticipantSessionsRequest, dict, ], ) -def test_list_participants_rest_call_success(request_type): +def test_list_participant_sessions_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantsResponse( + return_value = service.ListParticipantSessionsResponse( next_page_token="next_page_token_value", - total_size=1086, ) # Wrap the value into a proper Response obj @@ -9761,21 +11384,20 @@ def test_list_participants_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantsResponse.pb(return_value) + return_value = service.ListParticipantSessionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participants(request) + response = client.list_participant_sessions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) + assert isinstance(response, pagers.ListParticipantSessionsPager) assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_participants_rest_interceptors(null_interceptor): +def test_list_participant_sessions_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9788,21 +11410,23 @@ def test_list_participants_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_list_participants" + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_participant_sessions", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_participants_with_metadata", + "post_list_participant_sessions_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_list_participants" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_list_participant_sessions", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListParticipantsRequest.pb( - service.ListParticipantsRequest() + pb_message = service.ListParticipantSessionsRequest.pb( + service.ListParticipantSessionsRequest() ) transcode.return_value = { "method": "post", @@ -9814,21 +11438,24 @@ def test_list_participants_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListParticipantsResponse.to_json( - service.ListParticipantsResponse() + return_value = service.ListParticipantSessionsResponse.to_json( + service.ListParticipantSessionsResponse() ) req.return_value.content = return_value - request = service.ListParticipantsRequest() + request = service.ListParticipantSessionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListParticipantsResponse() - post_with_metadata.return_value = service.ListParticipantsResponse(), metadata + post.return_value = service.ListParticipantSessionsResponse() + post_with_metadata.return_value = ( + service.ListParticipantSessionsResponse(), + metadata, + ) - client.list_participants( + client.list_participant_sessions( request, metadata=[ ("key", "val"), @@ -9841,16 +11468,12 @@ def test_list_participants_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_participant_session_rest_bad_request( - request_type=service.GetParticipantSessionRequest, -): +def test_get_recording_rest_bad_request(request_type=service.GetRecordingRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" - } + request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9866,32 +11489,31 @@ def test_get_participant_session_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_participant_session(request) + client.get_recording(request) @pytest.mark.parametrize( "request_type", [ - service.GetParticipantSessionRequest, + service.GetRecordingRequest, dict, ], ) -def test_get_participant_session_rest_call_success(request_type): +def test_get_recording_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/participants/sample2/participantSessions/sample3" - } + request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.ParticipantSession( + return_value = resource.Recording( name="name_value", + state=resource.Recording.State.STARTED, ) # Wrap the value into a proper Response obj @@ -9899,20 +11521,21 @@ def test_get_participant_session_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.ParticipantSession.pb(return_value) + return_value = resource.Recording.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_participant_session(request) + response = client.get_recording(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.ParticipantSession) + assert isinstance(response, resource.Recording) assert response.name == "name_value" + assert response.state == resource.Recording.State.STARTED @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_participant_session_rest_interceptors(null_interceptor): +def test_get_recording_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9925,24 +11548,20 @@ def test_get_participant_session_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_get_participant_session", + transports.ConferenceRecordsServiceRestInterceptor, "post_get_recording" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_participant_session_with_metadata", + "post_get_recording_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_get_participant_session", + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_recording" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetParticipantSessionRequest.pb( - service.GetParticipantSessionRequest() - ) + pb_message = service.GetRecordingRequest.pb(service.GetRecordingRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9953,21 +11572,19 @@ def test_get_participant_session_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.ParticipantSession.to_json( - resource.ParticipantSession() - ) + return_value = resource.Recording.to_json(resource.Recording()) req.return_value.content = return_value - request = service.GetParticipantSessionRequest() + request = service.GetRecordingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.ParticipantSession() - post_with_metadata.return_value = resource.ParticipantSession(), metadata + post.return_value = resource.Recording() + post_with_metadata.return_value = resource.Recording(), metadata - client.get_participant_session( + client.get_recording( request, metadata=[ ("key", "val"), @@ -9980,14 +11597,12 @@ def test_get_participant_session_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_participant_sessions_rest_bad_request( - request_type=service.ListParticipantSessionsRequest, -): +def test_list_recordings_rest_bad_request(request_type=service.ListRecordingsRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10003,29 +11618,29 @@ def test_list_participant_sessions_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_participant_sessions(request) + client.list_recordings(request) @pytest.mark.parametrize( "request_type", [ - service.ListParticipantSessionsRequest, + service.ListRecordingsRequest, dict, ], ) -def test_list_participant_sessions_rest_call_success(request_type): +def test_list_recordings_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/participants/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListParticipantSessionsResponse( + return_value = service.ListRecordingsResponse( next_page_token="next_page_token_value", ) @@ -10034,20 +11649,20 @@ def test_list_participant_sessions_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListParticipantSessionsResponse.pb(return_value) + return_value = service.ListRecordingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_participant_sessions(request) + response = client.list_recordings(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantSessionsPager) + assert isinstance(response, pagers.ListRecordingsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_participant_sessions_rest_interceptors(null_interceptor): +def test_list_recordings_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10060,24 +11675,20 @@ def test_list_participant_sessions_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_list_participant_sessions", + transports.ConferenceRecordsServiceRestInterceptor, "post_list_recordings" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_participant_sessions_with_metadata", + "post_list_recordings_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_list_participant_sessions", + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_recordings" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListParticipantSessionsRequest.pb( - service.ListParticipantSessionsRequest() - ) + pb_message = service.ListRecordingsRequest.pb(service.ListRecordingsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10088,24 +11699,21 @@ def test_list_participant_sessions_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListParticipantSessionsResponse.to_json( - service.ListParticipantSessionsResponse() + return_value = service.ListRecordingsResponse.to_json( + service.ListRecordingsResponse() ) req.return_value.content = return_value - request = service.ListParticipantSessionsRequest() + request = service.ListRecordingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListParticipantSessionsResponse() - post_with_metadata.return_value = ( - service.ListParticipantSessionsResponse(), - metadata, - ) + post.return_value = service.ListRecordingsResponse() + post_with_metadata.return_value = service.ListRecordingsResponse(), metadata - client.list_participant_sessions( + client.list_recordings( request, metadata=[ ("key", "val"), @@ -10118,12 +11726,12 @@ def test_list_participant_sessions_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_recording_rest_bad_request(request_type=service.GetRecordingRequest): +def test_get_transcript_rest_bad_request(request_type=service.GetTranscriptRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} + request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10139,31 +11747,31 @@ def test_get_recording_rest_bad_request(request_type=service.GetRecordingRequest response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_recording(request) + client.get_transcript(request) @pytest.mark.parametrize( "request_type", [ - service.GetRecordingRequest, + service.GetTranscriptRequest, dict, ], ) -def test_get_recording_rest_call_success(request_type): +def test_get_transcript_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/recordings/sample2"} + request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Recording( + return_value = resource.Transcript( name="name_value", - state=resource.Recording.State.STARTED, + state=resource.Transcript.State.STARTED, ) # Wrap the value into a proper Response obj @@ -10171,21 +11779,21 @@ def test_get_recording_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Recording.pb(return_value) + return_value = resource.Transcript.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_recording(request) + response = client.get_transcript(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Recording) + assert isinstance(response, resource.Transcript) assert response.name == "name_value" - assert response.state == resource.Recording.State.STARTED + assert response.state == resource.Transcript.State.STARTED @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_recording_rest_interceptors(null_interceptor): +def test_get_transcript_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10198,20 +11806,20 @@ def test_get_recording_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_get_recording" + transports.ConferenceRecordsServiceRestInterceptor, "post_get_transcript" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_recording_with_metadata", + "post_get_transcript_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_get_recording" + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_transcript" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetRecordingRequest.pb(service.GetRecordingRequest()) + pb_message = service.GetTranscriptRequest.pb(service.GetTranscriptRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10222,19 +11830,19 @@ def test_get_recording_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Recording.to_json(resource.Recording()) + return_value = resource.Transcript.to_json(resource.Transcript()) req.return_value.content = return_value - request = service.GetRecordingRequest() + request = service.GetTranscriptRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Recording() - post_with_metadata.return_value = resource.Recording(), metadata + post.return_value = resource.Transcript() + post_with_metadata.return_value = resource.Transcript(), metadata - client.get_recording( + client.get_transcript( request, metadata=[ ("key", "val"), @@ -10247,7 +11855,7 @@ def test_get_recording_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_recordings_rest_bad_request(request_type=service.ListRecordingsRequest): +def test_list_transcripts_rest_bad_request(request_type=service.ListTranscriptsRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10268,17 +11876,17 @@ def test_list_recordings_rest_bad_request(request_type=service.ListRecordingsReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_recordings(request) + client.list_transcripts(request) @pytest.mark.parametrize( "request_type", [ - service.ListRecordingsRequest, + service.ListTranscriptsRequest, dict, ], ) -def test_list_recordings_rest_call_success(request_type): +def test_list_transcripts_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10290,7 +11898,7 @@ def test_list_recordings_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListRecordingsResponse( + return_value = service.ListTranscriptsResponse( next_page_token="next_page_token_value", ) @@ -10299,20 +11907,20 @@ def test_list_recordings_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRecordingsResponse.pb(return_value) + return_value = service.ListTranscriptsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_recordings(request) + response = client.list_transcripts(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRecordingsPager) + assert isinstance(response, pagers.ListTranscriptsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_recordings_rest_interceptors(null_interceptor): +def test_list_transcripts_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10325,20 +11933,20 @@ def test_list_recordings_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_list_recordings" + transports.ConferenceRecordsServiceRestInterceptor, "post_list_transcripts" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_recordings_with_metadata", + "post_list_transcripts_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_list_recordings" + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_transcripts" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListRecordingsRequest.pb(service.ListRecordingsRequest()) + pb_message = service.ListTranscriptsRequest.pb(service.ListTranscriptsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10349,21 +11957,21 @@ def test_list_recordings_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListRecordingsResponse.to_json( - service.ListRecordingsResponse() + return_value = service.ListTranscriptsResponse.to_json( + service.ListTranscriptsResponse() ) req.return_value.content = return_value - request = service.ListRecordingsRequest() + request = service.ListTranscriptsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListRecordingsResponse() - post_with_metadata.return_value = service.ListRecordingsResponse(), metadata + post.return_value = service.ListTranscriptsResponse() + post_with_metadata.return_value = service.ListTranscriptsResponse(), metadata - client.list_recordings( + client.list_transcripts( request, metadata=[ ("key", "val"), @@ -10376,12 +11984,16 @@ def test_list_recordings_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_transcript_rest_bad_request(request_type=service.GetTranscriptRequest): +def test_get_transcript_entry_rest_bad_request( + request_type=service.GetTranscriptEntryRequest, +): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} + request_init = { + "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10397,31 +12009,35 @@ def test_get_transcript_rest_bad_request(request_type=service.GetTranscriptReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript(request) + client.get_transcript_entry(request) @pytest.mark.parametrize( "request_type", [ - service.GetTranscriptRequest, + service.GetTranscriptEntryRequest, dict, ], ) -def test_get_transcript_rest_call_success(request_type): +def test_get_transcript_entry_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "conferenceRecords/sample1/transcripts/sample2"} + request_init = { + "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Transcript( + return_value = resource.TranscriptEntry( name="name_value", - state=resource.Transcript.State.STARTED, + participant="participant_value", + text="text_value", + language_code="language_code_value", ) # Wrap the value into a proper Response obj @@ -10429,21 +12045,23 @@ def test_get_transcript_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Transcript.pb(return_value) + return_value = resource.TranscriptEntry.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript(request) + response = client.get_transcript_entry(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Transcript) + assert isinstance(response, resource.TranscriptEntry) assert response.name == "name_value" - assert response.state == resource.Transcript.State.STARTED + assert response.participant == "participant_value" + assert response.text == "text_value" + assert response.language_code == "language_code_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_transcript_rest_interceptors(null_interceptor): +def test_get_transcript_entry_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10456,20 +12074,24 @@ def test_get_transcript_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_get_transcript" + transports.ConferenceRecordsServiceRestInterceptor, + "post_get_transcript_entry", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_transcript_with_metadata", + "post_get_transcript_entry_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_get_transcript" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_get_transcript_entry", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetTranscriptRequest.pb(service.GetTranscriptRequest()) + pb_message = service.GetTranscriptEntryRequest.pb( + service.GetTranscriptEntryRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10480,19 +12102,19 @@ def test_get_transcript_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Transcript.to_json(resource.Transcript()) + return_value = resource.TranscriptEntry.to_json(resource.TranscriptEntry()) req.return_value.content = return_value - request = service.GetTranscriptRequest() + request = service.GetTranscriptEntryRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Transcript() - post_with_metadata.return_value = resource.Transcript(), metadata + post.return_value = resource.TranscriptEntry() + post_with_metadata.return_value = resource.TranscriptEntry(), metadata - client.get_transcript( + client.get_transcript_entry( request, metadata=[ ("key", "val"), @@ -10505,12 +12127,14 @@ def test_get_transcript_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_transcripts_rest_bad_request(request_type=service.ListTranscriptsRequest): +def test_list_transcript_entries_rest_bad_request( + request_type=service.ListTranscriptEntriesRequest, +): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10526,29 +12150,29 @@ def test_list_transcripts_rest_bad_request(request_type=service.ListTranscriptsR response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcripts(request) + client.list_transcript_entries(request) @pytest.mark.parametrize( "request_type", [ - service.ListTranscriptsRequest, + service.ListTranscriptEntriesRequest, dict, ], ) -def test_list_transcripts_rest_call_success(request_type): +def test_list_transcript_entries_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1"} + request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptsResponse( + return_value = service.ListTranscriptEntriesResponse( next_page_token="next_page_token_value", ) @@ -10557,20 +12181,20 @@ def test_list_transcripts_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptsResponse.pb(return_value) + return_value = service.ListTranscriptEntriesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcripts(request) + response = client.list_transcript_entries(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTranscriptsPager) + assert isinstance(response, pagers.ListTranscriptEntriesPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_transcripts_rest_interceptors(null_interceptor): +def test_list_transcript_entries_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10583,20 +12207,24 @@ def test_list_transcripts_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "post_list_transcripts" + transports.ConferenceRecordsServiceRestInterceptor, + "post_list_transcript_entries", ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_transcripts_with_metadata", + "post_list_transcript_entries_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, "pre_list_transcripts" + transports.ConferenceRecordsServiceRestInterceptor, + "pre_list_transcript_entries", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListTranscriptsRequest.pb(service.ListTranscriptsRequest()) + pb_message = service.ListTranscriptEntriesRequest.pb( + service.ListTranscriptEntriesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10607,21 +12235,24 @@ def test_list_transcripts_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListTranscriptsResponse.to_json( - service.ListTranscriptsResponse() + return_value = service.ListTranscriptEntriesResponse.to_json( + service.ListTranscriptEntriesResponse() ) req.return_value.content = return_value - request = service.ListTranscriptsRequest() + request = service.ListTranscriptEntriesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListTranscriptsResponse() - post_with_metadata.return_value = service.ListTranscriptsResponse(), metadata + post.return_value = service.ListTranscriptEntriesResponse() + post_with_metadata.return_value = ( + service.ListTranscriptEntriesResponse(), + metadata, + ) - client.list_transcripts( + client.list_transcript_entries( request, metadata=[ ("key", "val"), @@ -10634,16 +12265,12 @@ def test_list_transcripts_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_transcript_entry_rest_bad_request( - request_type=service.GetTranscriptEntryRequest, -): +def test_get_smart_note_rest_bad_request(request_type=service.GetSmartNoteRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" - } + request_init = {"name": "conferenceRecords/sample1/smartNotes/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10659,35 +12286,31 @@ def test_get_transcript_entry_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_transcript_entry(request) + client.get_smart_note(request) @pytest.mark.parametrize( "request_type", [ - service.GetTranscriptEntryRequest, + service.GetSmartNoteRequest, dict, ], ) -def test_get_transcript_entry_rest_call_success(request_type): +def test_get_smart_note_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "conferenceRecords/sample1/transcripts/sample2/entries/sample3" - } + request_init = {"name": "conferenceRecords/sample1/smartNotes/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.TranscriptEntry( + return_value = resource.SmartNote( name="name_value", - participant="participant_value", - text="text_value", - language_code="language_code_value", + state=resource.SmartNote.State.STARTED, ) # Wrap the value into a proper Response obj @@ -10695,23 +12318,21 @@ def test_get_transcript_entry_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.TranscriptEntry.pb(return_value) + return_value = resource.SmartNote.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_transcript_entry(request) + response = client.get_smart_note(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.TranscriptEntry) + assert isinstance(response, resource.SmartNote) assert response.name == "name_value" - assert response.participant == "participant_value" - assert response.text == "text_value" - assert response.language_code == "language_code_value" + assert response.state == resource.SmartNote.State.STARTED @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_transcript_entry_rest_interceptors(null_interceptor): +def test_get_smart_note_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10724,24 +12345,20 @@ def test_get_transcript_entry_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_get_transcript_entry", + transports.ConferenceRecordsServiceRestInterceptor, "post_get_smart_note" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_get_transcript_entry_with_metadata", + "post_get_smart_note_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_get_transcript_entry", + transports.ConferenceRecordsServiceRestInterceptor, "pre_get_smart_note" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetTranscriptEntryRequest.pb( - service.GetTranscriptEntryRequest() - ) + pb_message = service.GetSmartNoteRequest.pb(service.GetSmartNoteRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10752,19 +12369,19 @@ def test_get_transcript_entry_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.TranscriptEntry.to_json(resource.TranscriptEntry()) + return_value = resource.SmartNote.to_json(resource.SmartNote()) req.return_value.content = return_value - request = service.GetTranscriptEntryRequest() + request = service.GetSmartNoteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.TranscriptEntry() - post_with_metadata.return_value = resource.TranscriptEntry(), metadata + post.return_value = resource.SmartNote() + post_with_metadata.return_value = resource.SmartNote(), metadata - client.get_transcript_entry( + client.get_smart_note( request, metadata=[ ("key", "val"), @@ -10777,14 +12394,12 @@ def test_get_transcript_entry_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_transcript_entries_rest_bad_request( - request_type=service.ListTranscriptEntriesRequest, -): +def test_list_smart_notes_rest_bad_request(request_type=service.ListSmartNotesRequest): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10800,29 +12415,29 @@ def test_list_transcript_entries_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_transcript_entries(request) + client.list_smart_notes(request) @pytest.mark.parametrize( "request_type", [ - service.ListTranscriptEntriesRequest, + service.ListSmartNotesRequest, dict, ], ) -def test_list_transcript_entries_rest_call_success(request_type): +def test_list_smart_notes_rest_call_success(request_type): client = ConferenceRecordsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "conferenceRecords/sample1/transcripts/sample2"} + request_init = {"parent": "conferenceRecords/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListTranscriptEntriesResponse( + return_value = service.ListSmartNotesResponse( next_page_token="next_page_token_value", ) @@ -10831,20 +12446,20 @@ def test_list_transcript_entries_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListTranscriptEntriesResponse.pb(return_value) + return_value = service.ListSmartNotesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_transcript_entries(request) + response = client.list_smart_notes(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTranscriptEntriesPager) + assert isinstance(response, pagers.ListSmartNotesPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_transcript_entries_rest_interceptors(null_interceptor): +def test_list_smart_notes_rest_interceptors(null_interceptor): transport = transports.ConferenceRecordsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10857,24 +12472,20 @@ def test_list_transcript_entries_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "post_list_transcript_entries", + transports.ConferenceRecordsServiceRestInterceptor, "post_list_smart_notes" ) as post, mock.patch.object( transports.ConferenceRecordsServiceRestInterceptor, - "post_list_transcript_entries_with_metadata", + "post_list_smart_notes_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConferenceRecordsServiceRestInterceptor, - "pre_list_transcript_entries", + transports.ConferenceRecordsServiceRestInterceptor, "pre_list_smart_notes" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListTranscriptEntriesRequest.pb( - service.ListTranscriptEntriesRequest() - ) + pb_message = service.ListSmartNotesRequest.pb(service.ListSmartNotesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10885,24 +12496,21 @@ def test_list_transcript_entries_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListTranscriptEntriesResponse.to_json( - service.ListTranscriptEntriesResponse() + return_value = service.ListSmartNotesResponse.to_json( + service.ListSmartNotesResponse() ) req.return_value.content = return_value - request = service.ListTranscriptEntriesRequest() + request = service.ListSmartNotesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListTranscriptEntriesResponse() - post_with_metadata.return_value = ( - service.ListTranscriptEntriesResponse(), - metadata, - ) + post.return_value = service.ListSmartNotesResponse() + post_with_metadata.return_value = service.ListSmartNotesResponse(), metadata - client.list_transcript_entries( + client.list_smart_notes( request, metadata=[ ("key", "val"), @@ -11164,6 +12772,44 @@ def test_list_transcript_entries_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_smart_note_empty_call_rest(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_smart_note), "__call__") as call: + client.get_smart_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetSmartNoteRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_smart_notes_empty_call_rest(): + client = ConferenceRecordsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_smart_notes), "__call__") as call: + client.list_smart_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListSmartNotesRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ConferenceRecordsServiceClient( @@ -11209,6 +12855,8 @@ def test_conference_records_service_base_transport(): "list_transcripts", "get_transcript_entry", "list_transcript_entries", + "get_smart_note", + "list_smart_notes", ) for method in methods: with pytest.raises(NotImplementedError): @@ -11524,6 +13172,12 @@ def test_conference_records_service_client_transport_session_collision(transport session1 = client1.transport.list_transcript_entries._session session2 = client2.transport.list_transcript_entries._session assert session1 != session2 + session1 = client1.transport.get_smart_note._session + session2 = client2.transport.get_smart_note._session + assert session1 != session2 + session1 = client1.transport.list_smart_notes._session + session2 = client2.transport.list_smart_notes._session + assert session1 != session2 def test_conference_records_service_grpc_transport_channel(): @@ -11751,8 +13405,33 @@ def test_parse_recording_path(): assert expected == actual +def test_smart_note_path(): + conference_record = "oyster" + smart_note = "nudibranch" + expected = "conferenceRecords/{conference_record}/smartNotes/{smart_note}".format( + conference_record=conference_record, + smart_note=smart_note, + ) + actual = ConferenceRecordsServiceClient.smart_note_path( + conference_record, smart_note + ) + assert expected == actual + + +def test_parse_smart_note_path(): + expected = { + "conference_record": "cuttlefish", + "smart_note": "mussel", + } + path = ConferenceRecordsServiceClient.smart_note_path(**expected) + + # Check that the path construction is reversible. + actual = ConferenceRecordsServiceClient.parse_smart_note_path(path) + assert expected == actual + + def test_space_path(): - space = "oyster" + space = "winkle" expected = "spaces/{space}".format( space=space, ) @@ -11762,7 +13441,7 @@ def test_space_path(): def test_parse_space_path(): expected = { - "space": "nudibranch", + "space": "nautilus", } path = ConferenceRecordsServiceClient.space_path(**expected) @@ -11772,8 +13451,8 @@ def test_parse_space_path(): def test_transcript_path(): - conference_record = "cuttlefish" - transcript = "mussel" + conference_record = "scallop" + transcript = "abalone" expected = "conferenceRecords/{conference_record}/transcripts/{transcript}".format( conference_record=conference_record, transcript=transcript, @@ -11786,8 +13465,8 @@ def test_transcript_path(): def test_parse_transcript_path(): expected = { - "conference_record": "winkle", - "transcript": "nautilus", + "conference_record": "squid", + "transcript": "clam", } path = ConferenceRecordsServiceClient.transcript_path(**expected) @@ -11797,9 +13476,9 @@ def test_parse_transcript_path(): def test_transcript_entry_path(): - conference_record = "scallop" - transcript = "abalone" - entry = "squid" + conference_record = "whelk" + transcript = "octopus" + entry = "oyster" expected = "conferenceRecords/{conference_record}/transcripts/{transcript}/entries/{entry}".format( conference_record=conference_record, transcript=transcript, @@ -11813,9 +13492,9 @@ def test_transcript_entry_path(): def test_parse_transcript_entry_path(): expected = { - "conference_record": "clam", - "transcript": "whelk", - "entry": "octopus", + "conference_record": "nudibranch", + "transcript": "cuttlefish", + "entry": "mussel", } path = ConferenceRecordsServiceClient.transcript_entry_path(**expected) @@ -11825,7 +13504,7 @@ def test_parse_transcript_entry_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -11835,7 +13514,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "nautilus", } path = ConferenceRecordsServiceClient.common_billing_account_path(**expected) @@ -11845,7 +13524,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -11855,7 +13534,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "abalone", } path = ConferenceRecordsServiceClient.common_folder_path(**expected) @@ -11865,7 +13544,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -11875,7 +13554,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "clam", } path = ConferenceRecordsServiceClient.common_organization_path(**expected) @@ -11885,7 +13564,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -11895,7 +13574,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "octopus", } path = ConferenceRecordsServiceClient.common_project_path(**expected) @@ -11905,8 +13584,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -11917,8 +13596,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "cuttlefish", + "location": "mussel", } path = ConferenceRecordsServiceClient.common_location_path(**expected) diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py index af9adc6e2f4a..038bbe262c8b 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore from google.api_core import ( client_options, @@ -4178,6 +4179,596 @@ async def test_delete_member_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMemberRequest(), + {}, + ], +) +def test_update_member(request_type, transport: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + user="user_value", + ) + response = client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + assert response.user == "user_value" + + +def test_update_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateMemberRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +def test_update_member_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_member in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_member] = mock_rpc + request = {} + client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_member + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_member + ] = mock_rpc + + request = {} + await client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMemberRequest(), + {}, + ], +) +async def test_update_member_async(request_type, transport: str = "grpc_asyncio"): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + user="user_value", + ) + ) + response = await client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + assert response.user == "user_value" + + +def test_update_member_field_headers(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMemberRequest() + + request.member.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value = resource.Member() + client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "member.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_member_field_headers_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMemberRequest() + + request.member.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + await client.update_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "member.name=name_value", + ) in kw["metadata"] + + +def test_update_member_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_member( + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].member + mock_val = resource.Member(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_member_flattened_error(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_member( + service.UpdateMemberRequest(), + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_member_flattened_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resource.Member() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.Member()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_member( + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].member + mock_val = resource.Member(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_member_flattened_error_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_member( + service.UpdateMemberRequest(), + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.BatchUpdateMembersRequest(), + {}, + ], +) +def test_batch_update_members(request_type, transport: str = "grpc"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.BatchUpdateMembersResponse() + response = client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.BatchUpdateMembersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.BatchUpdateMembersResponse) + + +def test_batch_update_members_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.BatchUpdateMembersRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_update_members(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_batch_update_members_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_update_members in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.batch_update_members] = ( + mock_rpc + ) + request = {} + client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_update_members_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_update_members + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_update_members + ] = mock_rpc + + request = {} + await client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_update_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.BatchUpdateMembersRequest(), + {}, + ], +) +async def test_batch_update_members_async( + request_type, transport: str = "grpc_asyncio" +): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.BatchUpdateMembersResponse() + ) + response = await client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.BatchUpdateMembersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.BatchUpdateMembersResponse) + + +def test_batch_update_members_field_headers(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchUpdateMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value = service.BatchUpdateMembersResponse() + client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_update_members_field_headers_async(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.BatchUpdateMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.BatchUpdateMembersResponse() + ) + await client.batch_update_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + def test_create_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4207,14 +4798,343 @@ def test_create_space_rest_use_cached_wrapped_rpc(): # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_space(request) + client.create_space(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_space_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + space=resource.Space(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/spaces" % client.transport._host, args[1] + ) + + +def test_create_space_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_space( + service.CreateSpaceRequest(), + space=resource.Space(name="name_value"), + ) + + +def test_get_space_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_space in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_space] = mock_rpc + + request = {} + client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_space(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetSpace, + "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_space_rest_flattened(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_space(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{name=spaces/*}" % client.transport._host, args[1] + ) + + +def test_get_space_rest_flattened_error(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_space( + service.GetSpaceRequest(), + name="name_value", + ) + + +def test_update_space_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_space in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_space] = mock_rpc + + request = {} + client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_space_rest_flattened(): +def test_update_space_rest_required_fields(request_type=service.UpdateSpaceRequest): + transport_class = transports.SpacesServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateSpace, + "_BaseUpdateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_space_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4226,11 +5146,12 @@ def test_create_space_rest_flattened(): return_value = resource.Space() # get arguments that satisfy an http rule for this method - sample_request = {} + sample_request = {"space": {"name": "spaces/sample1"}} # get truthy value for each flattened field mock_args = dict( space=resource.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -4244,18 +5165,18 @@ def test_create_space_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_space(**mock_args) + client.update_space(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/spaces" % client.transport._host, args[1] + "%s/v2beta/{space.name=spaces/*}" % client.transport._host, args[1] ) -def test_create_space_rest_flattened_error(transport: str = "rest"): +def test_update_space_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4264,13 +5185,14 @@ def test_create_space_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_space( - service.CreateSpaceRequest(), + client.update_space( + service.UpdateSpaceRequest(), space=resource.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_space_rest_use_cached_wrapped_rpc(): +def test_connect_active_conference_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4284,33 +5206,41 @@ def test_get_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_space in client._transport._wrapped_methods + assert ( + client._transport.connect_active_conference + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_space] = mock_rpc + client._transport._wrapped_methods[ + client._transport.connect_active_conference + ] = mock_rpc request = {} - client.get_space(request) + client.connect_active_conference(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space(request) + client.connect_active_conference(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): +def test_connect_active_conference_rest_required_fields( + request_type=service.ConnectActiveConferenceRequest, +): transport_class = transports.SpacesServiceRestTransport request_init = {} request_init["name"] = "" + request_init["offer"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4320,8 +5250,8 @@ def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetSpace, - "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseConnectActiveConference, + "_BaseConnectActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -4332,10 +5262,13 @@ def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): # verify required fields with default values are now present jsonified_request["name"] = "name_value" + jsonified_request["offer"] = "offer_value" # verify required fields with non-default values are left alone assert "name" in jsonified_request assert jsonified_request["name"] == "name_value" + assert "offer" in jsonified_request + assert jsonified_request["offer"] == "offer_value" client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4344,7 +5277,7 @@ def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Space() + return_value = service.ConnectActiveConferenceResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4356,30 +5289,31 @@ def test_get_space_rest_required_fields(request_type=service.GetSpaceRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) + return_value = service.ConnectActiveConferenceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_space(request) + response = client.connect_active_conference(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_space_rest_flattened(): +def test_connect_active_conference_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4388,7 +5322,7 @@ def test_get_space_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Space() + return_value = service.ConnectActiveConferenceResponse() # get arguments that satisfy an http rule for this method sample_request = {"name": "spaces/sample1"} @@ -4403,24 +5337,26 @@ def test_get_space_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) + return_value = service.ConnectActiveConferenceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_space(**mock_args) + client.connect_active_conference(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=spaces/*}" % client.transport._host, args[1] + "%s/v2beta/{name=spaces/*}:connectActiveConference" + % client.transport._host, + args[1], ) -def test_get_space_rest_flattened_error(transport: str = "rest"): +def test_connect_active_conference_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4429,13 +5365,13 @@ def test_get_space_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_space( - service.GetSpaceRequest(), + client.connect_active_conference( + service.ConnectActiveConferenceRequest(), name="name_value", ) -def test_update_space_rest_use_cached_wrapped_rpc(): +def test_end_active_conference_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4449,32 +5385,40 @@ def test_update_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_space in client._transport._wrapped_methods + assert ( + client._transport.end_active_conference + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_space] = mock_rpc + client._transport._wrapped_methods[client._transport.end_active_conference] = ( + mock_rpc + ) request = {} - client.update_space(request) + client.end_active_conference(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_space(request) + client.end_active_conference(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_space_rest_required_fields(request_type=service.UpdateSpaceRequest): +def test_end_active_conference_rest_required_fields( + request_type=service.EndActiveConferenceRequest, +): transport_class = transports.SpacesServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4484,8 +5428,8 @@ def test_update_space_rest_required_fields(request_type=service.UpdateSpaceReque # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateSpace, - "_BaseUpdateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseEndActiveConference, + "_BaseEndActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -4495,10 +5439,11 @@ def test_update_space_rest_required_fields(request_type=service.UpdateSpaceReque # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("updateMask",)) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4507,7 +5452,7 @@ def test_update_space_rest_required_fields(request_type=service.UpdateSpaceReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Space() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4519,7 +5464,7 @@ def test_update_space_rest_required_fields(request_type=service.UpdateSpaceReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -4527,23 +5472,20 @@ def test_update_space_rest_required_fields(request_type=service.UpdateSpaceReque response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_space(request) + response = client.end_active_conference(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_space_rest_flattened(): +def test_end_active_conference_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4552,40 +5494,38 @@ def test_update_space_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Space() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"space": {"name": "spaces/sample1"}} + sample_request = {"name": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - space=resource.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_space(**mock_args) + client.end_active_conference(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{space.name=spaces/*}" % client.transport._host, args[1] + "%s/v2beta/{name=spaces/*}:endActiveConference" % client.transport._host, + args[1], ) -def test_update_space_rest_flattened_error(transport: str = "rest"): +def test_end_active_conference_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4594,14 +5534,13 @@ def test_update_space_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_space( - service.UpdateSpaceRequest(), - space=resource.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.end_active_conference( + service.EndActiveConferenceRequest(), + name="name_value", ) -def test_connect_active_conference_rest_use_cached_wrapped_rpc(): +def test_create_member_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4615,41 +5554,33 @@ def test_connect_active_conference_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.connect_active_conference - in client._transport._wrapped_methods - ) + assert client._transport.create_member in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.connect_active_conference - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_member] = mock_rpc request = {} - client.connect_active_conference(request) + client.create_member(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.connect_active_conference(request) + client.create_member(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_connect_active_conference_rest_required_fields( - request_type=service.ConnectActiveConferenceRequest, -): +def test_create_member_rest_required_fields(request_type=service.CreateMemberRequest): transport_class = transports.SpacesServiceRestTransport request_init = {} - request_init["name"] = "" - request_init["offer"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4659,8 +5590,8 @@ def test_connect_active_conference_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseConnectActiveConference, - "_BaseConnectActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateMember, + "_BaseCreateMember__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -4670,14 +5601,11 @@ def test_connect_active_conference_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["offer"] = "offer_value" + jsonified_request["parent"] = "parent_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - assert "offer" in jsonified_request - assert jsonified_request["offer"] == "offer_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4686,7 +5614,7 @@ def test_connect_active_conference_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ConnectActiveConferenceResponse() + return_value = resource.Member() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4708,21 +5636,21 @@ def test_connect_active_conference_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ConnectActiveConferenceResponse.pb(return_value) + return_value = resource.Member.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.connect_active_conference(request) + response = client.create_member(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_connect_active_conference_rest_flattened(): +def test_create_member_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4731,14 +5659,15 @@ def test_connect_active_conference_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ConnectActiveConferenceResponse() + return_value = resource.Member() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + member=resource.Member(name="name_value"), ) mock_args.update(sample_request) @@ -4746,26 +5675,24 @@ def test_connect_active_conference_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ConnectActiveConferenceResponse.pb(return_value) + return_value = resource.Member.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.connect_active_conference(**mock_args) + client.create_member(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=spaces/*}:connectActiveConference" - % client.transport._host, - args[1], + "%s/v2beta/{parent=spaces/*}/members" % client.transport._host, args[1] ) -def test_connect_active_conference_rest_flattened_error(transport: str = "rest"): +def test_create_member_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4774,13 +5701,14 @@ def test_connect_active_conference_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.connect_active_conference( - service.ConnectActiveConferenceRequest(), - name="name_value", + client.create_member( + service.CreateMemberRequest(), + parent="parent_value", + member=resource.Member(name="name_value"), ) -def test_end_active_conference_rest_use_cached_wrapped_rpc(): +def test_get_member_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4794,36 +5722,29 @@ def test_end_active_conference_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.end_active_conference - in client._transport._wrapped_methods - ) + assert client._transport.get_member in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.end_active_conference] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_member] = mock_rpc request = {} - client.end_active_conference(request) + client.get_member(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.end_active_conference(request) + client.get_member(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_end_active_conference_rest_required_fields( - request_type=service.EndActiveConferenceRequest, -): +def test_get_member_rest_required_fields(request_type=service.GetMemberRequest): transport_class = transports.SpacesServiceRestTransport request_init = {} @@ -4837,8 +5758,8 @@ def test_end_active_conference_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseEndActiveConference, - "_BaseEndActiveConference__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetMember, + "_BaseGetMember__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -4861,7 +5782,7 @@ def test_end_active_conference_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resource.Member() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4873,28 +5794,30 @@ def test_end_active_conference_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.end_active_conference(request) + response = client.get_member(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_end_active_conference_rest_flattened(): +def test_get_member_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4903,10 +5826,10 @@ def test_end_active_conference_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resource.Member() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + sample_request = {"name": "spaces/sample1/members/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -4917,24 +5840,25 @@ def test_end_active_conference_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.end_active_conference(**mock_args) + client.get_member(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{name=spaces/*}:endActiveConference" % client.transport._host, - args[1], + "%s/v2beta/{name=spaces/*/members/*}" % client.transport._host, args[1] ) -def test_end_active_conference_rest_flattened_error(transport: str = "rest"): +def test_get_member_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4943,13 +5867,13 @@ def test_end_active_conference_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.end_active_conference( - service.EndActiveConferenceRequest(), + client.get_member( + service.GetMemberRequest(), name="name_value", ) -def test_create_member_rest_use_cached_wrapped_rpc(): +def test_list_members_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4963,29 +5887,29 @@ def test_create_member_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_member in client._transport._wrapped_methods + assert client._transport.list_members in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_member] = mock_rpc + client._transport._wrapped_methods[client._transport.list_members] = mock_rpc request = {} - client.create_member(request) + client.list_members(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_member(request) + client.list_members(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_member_rest_required_fields(request_type=service.CreateMemberRequest): +def test_list_members_rest_required_fields(request_type=service.ListMembersRequest): transport_class = transports.SpacesServiceRestTransport request_init = {} @@ -4999,8 +5923,8 @@ def test_create_member_rest_required_fields(request_type=service.CreateMemberReq # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateMember, - "_BaseCreateMember__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListMembers, + "_BaseListMembers__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5012,6 +5936,14 @@ def test_create_member_rest_required_fields(request_type=service.CreateMemberReq jsonified_request["parent"] = "parent_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" @@ -5023,7 +5955,7 @@ def test_create_member_rest_required_fields(request_type=service.CreateMemberReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Member() + return_value = service.ListMembersResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5035,31 +5967,30 @@ def test_create_member_rest_required_fields(request_type=service.CreateMemberReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Member.pb(return_value) + return_value = service.ListMembersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_member(request) + response = client.list_members(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_member_rest_flattened(): +def test_list_members_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5068,7 +5999,7 @@ def test_create_member_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Member() + return_value = service.ListMembersResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "spaces/sample1"} @@ -5076,7 +6007,6 @@ def test_create_member_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - member=resource.Member(name="name_value"), ) mock_args.update(sample_request) @@ -5084,13 +6014,13 @@ def test_create_member_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resource.Member.pb(return_value) + return_value = service.ListMembersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_member(**mock_args) + client.list_members(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -5101,7 +6031,7 @@ def test_create_member_rest_flattened(): ) -def test_create_member_rest_flattened_error(transport: str = "rest"): +def test_list_members_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5110,14 +6040,77 @@ def test_create_member_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_member( - service.CreateMemberRequest(), + client.list_members( + service.ListMembersRequest(), parent="parent_value", - member=resource.Member(name="name_value"), ) -def test_get_member_rest_use_cached_wrapped_rpc(): +def test_list_members_rest_pager(transport: str = "rest"): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + resource.Member(), + ], + next_page_token="abc", + ), + service.ListMembersResponse( + members=[], + next_page_token="def", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + ], + next_page_token="ghi", + ), + service.ListMembersResponse( + members=[ + resource.Member(), + resource.Member(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListMembersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "spaces/sample1"} + + pager = client.list_members(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.Member) for i in results) + + pages = list(client.list_members(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_member_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5131,29 +6124,29 @@ def test_get_member_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_member in client._transport._wrapped_methods + assert client._transport.delete_member in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_member] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_member] = mock_rpc request = {} - client.get_member(request) + client.delete_member(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_member(request) + client.delete_member(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_member_rest_required_fields(request_type=service.GetMemberRequest): +def test_delete_member_rest_required_fields(request_type=service.DeleteMemberRequest): transport_class = transports.SpacesServiceRestTransport request_init = {} @@ -5167,8 +6160,8 @@ def test_get_member_rest_required_fields(request_type=service.GetMemberRequest): # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetMember, - "_BaseGetMember__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteMember, + "_BaseDeleteMember__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5191,7 +6184,7 @@ def test_get_member_rest_required_fields(request_type=service.GetMemberRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resource.Member() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5203,30 +6196,27 @@ def test_get_member_rest_required_fields(request_type=service.GetMemberRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource.Member.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_member(request) + response = client.delete_member(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_member_rest_flattened(): +def test_delete_member_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5235,7 +6225,7 @@ def test_get_member_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Member() + return_value = None # get arguments that satisfy an http rule for this method sample_request = {"name": "spaces/sample1/members/sample2"} @@ -5249,14 +6239,12 @@ def test_get_member_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource.Member.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_member(**mock_args) + client.delete_member(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -5267,7 +6255,7 @@ def test_get_member_rest_flattened(): ) -def test_get_member_rest_flattened_error(transport: str = "rest"): +def test_delete_member_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5276,13 +6264,13 @@ def test_get_member_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_member( - service.GetMemberRequest(), + client.delete_member( + service.DeleteMemberRequest(), name="name_value", ) -def test_list_members_rest_use_cached_wrapped_rpc(): +def test_update_member_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5296,33 +6284,32 @@ def test_list_members_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_members in client._transport._wrapped_methods + assert client._transport.update_member in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_members] = mock_rpc + client._transport._wrapped_methods[client._transport.update_member] = mock_rpc request = {} - client.list_members(request) + client.update_member(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_members(request) + client.update_member(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_members_rest_required_fields(request_type=service.ListMembersRequest): +def test_update_member_rest_required_fields(request_type=service.UpdateMemberRequest): transport_class = transports.SpacesServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5332,8 +6319,8 @@ def test_list_members_rest_required_fields(request_type=service.ListMembersReque # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListMembers, - "_BaseListMembers__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateMember, + "_BaseUpdateMember__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5343,19 +6330,10 @@ def test_list_members_rest_required_fields(request_type=service.ListMembersReque # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", - ) - ) + assert not set(unset_fields) - set(("updateMask",)) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # verify required fields with non-default values are left alone client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5364,7 +6342,7 @@ def test_list_members_rest_required_fields(request_type=service.ListMembersReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListMembersResponse() + return_value = resource.Member() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5376,30 +6354,31 @@ def test_list_members_rest_required_fields(request_type=service.ListMembersReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListMembersResponse.pb(return_value) + return_value = resource.Member.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_members(request) + response = client.update_member(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_members_rest_flattened(): +def test_update_member_rest_flattened(): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5408,14 +6387,15 @@ def test_list_members_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListMembersResponse() + return_value = resource.Member() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + sample_request = {"member": {"name": "spaces/sample1/members/sample2"}} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -5423,24 +6403,25 @@ def test_list_members_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListMembersResponse.pb(return_value) + return_value = resource.Member.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_members(**mock_args) + client.update_member(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2beta/{parent=spaces/*}/members" % client.transport._host, args[1] + "%s/v2beta/{member.name=spaces/*/members/*}" % client.transport._host, + args[1], ) -def test_list_members_rest_flattened_error(transport: str = "rest"): +def test_update_member_rest_flattened_error(transport: str = "rest"): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5449,77 +6430,14 @@ def test_list_members_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_members( - service.ListMembersRequest(), - parent="parent_value", - ) - - -def test_list_members_rest_pager(transport: str = "rest"): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListMembersResponse( - members=[ - resource.Member(), - resource.Member(), - resource.Member(), - ], - next_page_token="abc", - ), - service.ListMembersResponse( - members=[], - next_page_token="def", - ), - service.ListMembersResponse( - members=[ - resource.Member(), - ], - next_page_token="ghi", - ), - service.ListMembersResponse( - members=[ - resource.Member(), - resource.Member(), - ], - ), + client.update_member( + service.UpdateMemberRequest(), + member=resource.Member(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListMembersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "spaces/sample1"} - - pager = client.list_members(request=sample_request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resource.Member) for i in results) - - pages = list(client.list_members(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - -def test_delete_member_rest_use_cached_wrapped_rpc(): +def test_batch_update_members_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5533,33 +6451,39 @@ def test_delete_member_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_member in client._transport._wrapped_methods + assert ( + client._transport.batch_update_members in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_member] = mock_rpc + client._transport._wrapped_methods[client._transport.batch_update_members] = ( + mock_rpc + ) request = {} - client.delete_member(request) + client.batch_update_members(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_member(request) + client.batch_update_members(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_member_rest_required_fields(request_type=service.DeleteMemberRequest): +def test_batch_update_members_rest_required_fields( + request_type=service.BatchUpdateMembersRequest, +): transport_class = transports.SpacesServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5569,8 +6493,8 @@ def test_delete_member_rest_required_fields(request_type=service.DeleteMemberReq # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteMember, - "_BaseDeleteMember__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseBatchUpdateMembers, + "_BaseBatchUpdateMembers__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5580,11 +6504,11 @@ def test_delete_member_rest_required_fields(request_type=service.DeleteMemberReq # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5593,7 +6517,7 @@ def test_delete_member_rest_required_fields(request_type=service.DeleteMemberReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = service.BatchUpdateMembersResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5605,80 +6529,30 @@ def test_delete_member_rest_required_fields(request_type=service.DeleteMemberReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = service.BatchUpdateMembersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_member(request) + response = client.batch_update_members(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_member_rest_flattened(): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/members/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_member(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2beta/{name=spaces/*/members/*}" % client.transport._host, args[1] - ) - - -def test_delete_member_rest_flattened_error(transport: str = "rest"): - client = SpacesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_member( - service.DeleteMemberRequest(), - name="name_value", - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SpacesServiceGrpcTransport( @@ -5969,6 +6843,48 @@ def test_delete_member_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_member_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + call.return_value = resource.Member() + client.update_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_members_empty_call_grpc(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + call.return_value = service.BatchUpdateMembersResponse() + client.batch_update_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = SpacesServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -6226,6 +7142,61 @@ async def test_delete_member_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_member_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + user="user_value", + ) + ) + await client.update_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_update_members_empty_call_grpc_asyncio(): + client = SpacesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.BatchUpdateMembersResponse() + ) + await client.batch_update_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest() + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = SpacesServiceClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -6292,7 +7263,21 @@ def test_create_space_rest_call_success(request_type): "smart_notes_config": {"auto_smart_notes_generation": 1}, }, }, - "active_conference": {"conference_record": "conference_record_value"}, + "active_conference": { + "conference_record": "conference_record_value", + "media_api_consenter_present": True, + }, + "phone_access": [ + { + "phone_number": "phone_number_value", + "pin": "pin_value", + "region_code": "region_code_value", + "language_code": "language_code_value", + } + ], + "gateway_sip_access": [ + {"uri": "uri_value", "sip_access_code": "sip_access_code_value"} + ], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -6642,7 +7627,21 @@ def test_update_space_rest_call_success(request_type): "smart_notes_config": {"auto_smart_notes_generation": 1}, }, }, - "active_conference": {"conference_record": "conference_record_value"}, + "active_conference": { + "conference_record": "conference_record_value", + "media_api_consenter_present": True, + }, + "phone_access": [ + { + "phone_number": "phone_number_value", + "pin": "pin_value", + "region_code": "region_code_value", + "language_code": "language_code_value", + } + ], + "gateway_sip_access": [ + {"uri": "uri_value", "sip_access_code": "sip_access_code_value"} + ], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -7195,7 +8194,265 @@ def get_message_fields(field): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_member_rest_interceptors(null_interceptor): +def test_create_member_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_create_member" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_create_member_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_create_member" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateMemberRequest.pb(service.CreateMemberRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.Member.to_json(resource.Member()) + req.return_value.content = return_value + + request = service.CreateMemberRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.Member() + post_with_metadata.return_value = resource.Member(), metadata + + client.create_member( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_member_rest_bad_request(request_type=service.GetMemberRequest): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_member(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetMemberRequest, + dict, + ], +) +def test_get_member_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + user="user_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource.Member.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_member(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + assert response.user == "user_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_member_rest_interceptors(null_interceptor): + transport = transports.SpacesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SpacesServiceRestInterceptor(), + ) + client = SpacesServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_get_member" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "post_get_member_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_get_member" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetMemberRequest.pb(service.GetMemberRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resource.Member.to_json(resource.Member()) + req.return_value.content = return_value + + request = service.GetMemberRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.Member() + post_with_metadata.return_value = resource.Member(), metadata + + client.get_member( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_members_rest_bad_request(request_type=service.ListMembersRequest): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_members(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembersRequest, + dict, + ], +) +def test_list_members_rest_call_success(request_type): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembersResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_members(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembersPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_members_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7208,19 +8465,19 @@ def test_create_member_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_create_member" + transports.SpacesServiceRestInterceptor, "post_list_members" ) as post, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_create_member_with_metadata" + transports.SpacesServiceRestInterceptor, "post_list_members_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_create_member" + transports.SpacesServiceRestInterceptor, "pre_list_members" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateMemberRequest.pb(service.CreateMemberRequest()) + pb_message = service.ListMembersRequest.pb(service.ListMembersRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7231,19 +8488,21 @@ def test_create_member_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Member.to_json(resource.Member()) + return_value = service.ListMembersResponse.to_json( + service.ListMembersResponse() + ) req.return_value.content = return_value - request = service.CreateMemberRequest() + request = service.ListMembersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Member() - post_with_metadata.return_value = resource.Member(), metadata + post.return_value = service.ListMembersResponse() + post_with_metadata.return_value = service.ListMembersResponse(), metadata - client.create_member( + client.list_members( request, metadata=[ ("key", "val"), @@ -7256,7 +8515,7 @@ def test_create_member_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_member_rest_bad_request(request_type=service.GetMemberRequest): +def test_delete_member_rest_bad_request(request_type=service.DeleteMemberRequest): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7277,17 +8536,17 @@ def test_get_member_rest_bad_request(request_type=service.GetMemberRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_member(request) + client.delete_member(request) @pytest.mark.parametrize( "request_type", [ - service.GetMemberRequest, + service.DeleteMemberRequest, dict, ], ) -def test_get_member_rest_call_success(request_type): +def test_delete_member_rest_call_success(request_type): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7299,35 +8558,23 @@ def test_get_member_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resource.Member( - name="name_value", - email="email_value", - role=resource.Member.Role.COHOST, - user="user_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource.Member.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_member(request) + response = client.delete_member(request) # Establish that the response is the type that we expect. - assert isinstance(response, resource.Member) - assert response.name == "name_value" - assert response.email == "email_value" - assert response.role == resource.Member.Role.COHOST - assert response.user == "user_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_member_rest_interceptors(null_interceptor): +def test_delete_member_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7340,19 +8587,11 @@ def test_get_member_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_get_member" - ) as post, - mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_get_member_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_get_member" + transports.SpacesServiceRestInterceptor, "pre_delete_member" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.GetMemberRequest.pb(service.GetMemberRequest()) + pb_message = service.DeleteMemberRequest.pb(service.DeleteMemberRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7363,19 +8602,15 @@ def test_get_member_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resource.Member.to_json(resource.Member()) - req.return_value.content = return_value - request = service.GetMemberRequest() + request = service.DeleteMemberRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resource.Member() - post_with_metadata.return_value = resource.Member(), metadata - client.get_member( + client.delete_member( request, metadata=[ ("key", "val"), @@ -7384,16 +8619,14 @@ def test_get_member_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_list_members_rest_bad_request(request_type=service.ListMembersRequest): +def test_update_member_rest_bad_request(request_type=service.UpdateMemberRequest): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} + request_init = {"member": {"name": "spaces/sample1/members/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -7409,30 +8642,106 @@ def test_list_members_rest_bad_request(request_type=service.ListMembersRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_members(request) + client.update_member(request) @pytest.mark.parametrize( "request_type", [ - service.ListMembersRequest, + service.UpdateMemberRequest, dict, ], ) -def test_list_members_rest_call_success(request_type): +def test_update_member_rest_call_success(request_type): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} + request_init = {"member": {"name": "spaces/sample1/members/sample2"}} + request_init["member"] = { + "name": "spaces/sample1/members/sample2", + "email": "email_value", + "role": 1, + "user": "user_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateMemberRequest.meta.fields["member"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["member"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["member"][field])): + del request_init["member"][field][i][subfield] + else: + del request_init["member"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListMembersResponse( - next_page_token="next_page_token_value", + return_value = resource.Member( + name="name_value", + email="email_value", + role=resource.Member.Role.COHOST, + user="user_value", ) # Wrap the value into a proper Response obj @@ -7440,20 +8749,23 @@ def test_list_members_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListMembersResponse.pb(return_value) + return_value = resource.Member.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_members(request) + response = client.update_member(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMembersPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resource.Member) + assert response.name == "name_value" + assert response.email == "email_value" + assert response.role == resource.Member.Role.COHOST + assert response.user == "user_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_members_rest_interceptors(null_interceptor): +def test_update_member_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7466,19 +8778,19 @@ def test_list_members_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_list_members" + transports.SpacesServiceRestInterceptor, "post_update_member" ) as post, mock.patch.object( - transports.SpacesServiceRestInterceptor, "post_list_members_with_metadata" + transports.SpacesServiceRestInterceptor, "post_update_member_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_list_members" + transports.SpacesServiceRestInterceptor, "pre_update_member" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListMembersRequest.pb(service.ListMembersRequest()) + pb_message = service.UpdateMemberRequest.pb(service.UpdateMemberRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7489,21 +8801,19 @@ def test_list_members_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListMembersResponse.to_json( - service.ListMembersResponse() - ) + return_value = resource.Member.to_json(resource.Member()) req.return_value.content = return_value - request = service.ListMembersRequest() + request = service.UpdateMemberRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListMembersResponse() - post_with_metadata.return_value = service.ListMembersResponse(), metadata + post.return_value = resource.Member() + post_with_metadata.return_value = resource.Member(), metadata - client.list_members( + client.update_member( request, metadata=[ ("key", "val"), @@ -7516,12 +8826,14 @@ def test_list_members_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_member_rest_bad_request(request_type=service.DeleteMemberRequest): +def test_batch_update_members_rest_bad_request( + request_type=service.BatchUpdateMembersRequest, +): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/members/sample2"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -7537,45 +8849,48 @@ def test_delete_member_rest_bad_request(request_type=service.DeleteMemberRequest response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_member(request) + client.batch_update_members(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteMemberRequest, + service.BatchUpdateMembersRequest, dict, ], ) -def test_delete_member_rest_call_success(request_type): +def test_batch_update_members_rest_call_success(request_type): client = SpacesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/members/sample2"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = service.BatchUpdateMembersResponse() # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = service.BatchUpdateMembersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_member(request) + response = client.batch_update_members(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, service.BatchUpdateMembersResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_member_rest_interceptors(null_interceptor): +def test_batch_update_members_rest_interceptors(null_interceptor): transport = transports.SpacesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7588,11 +8903,22 @@ def test_delete_member_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SpacesServiceRestInterceptor, "pre_delete_member" + transports.SpacesServiceRestInterceptor, "post_batch_update_members" + ) as post, + mock.patch.object( + transports.SpacesServiceRestInterceptor, + "post_batch_update_members_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SpacesServiceRestInterceptor, "pre_batch_update_members" ) as pre, ): pre.assert_not_called() - pb_message = service.DeleteMemberRequest.pb(service.DeleteMemberRequest()) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.BatchUpdateMembersRequest.pb( + service.BatchUpdateMembersRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7603,15 +8929,21 @@ def test_delete_member_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.BatchUpdateMembersResponse.to_json( + service.BatchUpdateMembersResponse() + ) + req.return_value.content = return_value - request = service.DeleteMemberRequest() + request = service.BatchUpdateMembersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = service.BatchUpdateMembersResponse() + post_with_metadata.return_value = service.BatchUpdateMembersResponse(), metadata - client.delete_member( + client.batch_update_members( request, metadata=[ ("key", "val"), @@ -7620,6 +8952,8 @@ def test_delete_member_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() def test_initialize_client_w_rest(): @@ -7804,6 +9138,46 @@ def test_delete_member_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_member_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_member), "__call__") as call: + client.update_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_members_empty_call_rest(): + client = SpacesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_members), "__call__" + ) as call: + client.batch_update_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.BatchUpdateMembersRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SpacesServiceClient( @@ -7846,6 +9220,8 @@ def test_spaces_service_base_transport(): "get_member", "list_members", "delete_member", + "update_member", + "batch_update_members", ) for method in methods: with pytest.raises(NotImplementedError): @@ -8164,6 +9540,12 @@ def test_spaces_service_client_transport_session_collision(transport_name): session1 = client1.transport.delete_member._session session2 = client2.transport.delete_member._session assert session1 != session2 + session1 = client1.transport.update_member._session + session2 = client2.transport.update_member._session + assert session1 != session2 + session1 = client1.transport.batch_update_members._session + session2 = client2.transport.batch_update_members._session + assert session1 != session2 def test_spaces_service_grpc_transport_channel(): diff --git a/packages/google-auth/setup.py b/packages/google-auth/setup.py index cff8a7bdbda9..8807e7eb342b 100644 --- a/packages/google-auth/setup.py +++ b/packages/google-auth/setup.py @@ -106,7 +106,7 @@ long_description=long_description, url="https://github.com/googleapis/google-cloud-python/tree/main/packages/google-auth", packages=find_namespace_packages( - exclude=("tests*", "system_tests*", "docs*", "samples*") + exclude=("tests*", "system_tests*", "docs*", "samples*", "build*") ), package_data={"google.auth": ["py.typed"], "google.oauth2": ["py.typed"]}, install_requires=DEPENDENCIES, diff --git a/packages/google-cloud-api-gateway/CHANGELOG.md b/packages/google-cloud-api-gateway/CHANGELOG.md index 480272b2737e..035403037f6a 100644 --- a/packages/google-cloud-api-gateway/CHANGELOG.md +++ b/packages/google-cloud-api-gateway/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-api-gateway/#history +## [1.17.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-gateway-v1.16.0...google-cloud-api-gateway-v1.17.0) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [1.16.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-gateway-v1.15.0...google-cloud-api-gateway-v1.16.0) (2026-06-02) diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py b/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py index 14edf824ad86..2095da2522f4 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.0" # {x-release-please-version} +__version__ = "1.17.0" # {x-release-please-version} diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py index 14edf824ad86..2095da2522f4 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.0" # {x-release-please-version} +__version__ = "1.17.0" # {x-release-please-version} diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/types/apigateway.py b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/types/apigateway.py index 983f5ee6547c..d703a81a5999 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/types/apigateway.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/types/apigateway.py @@ -375,8 +375,22 @@ class Gateway(proto.Message): Output only. The current state of the Gateway. default_hostname (str): - Output only. The default API Gateway host name of the form - ``{gateway_id}-{hash}.{region_code}.gateway.dev``. + Output only. The default hostname that serves + traffic for this Gateway. + streaming_mode (google.cloud.apigateway_v1.types.Gateway.StreamingMode): + Optional. Immutable. Requests streaming for a new gateway. + An attempt to change it on update is rejected. If unset, the + service selects the mode. This field records only what was + requested and is never modified by the service; read + ``effective_streaming_mode`` for the mode the gateway is + served with. + effective_streaming_mode (google.cloud.apigateway_v1.types.Gateway.EffectiveStreamingMode): + Output only. The streaming mode this gateway is actually + served with, which the service resolves at creation from + ``streaming_mode``, the referenced API Config, and the + platform default at the time. Read this rather than + ``streaming_mode`` to determine whether a gateway supports + streaming. """ class State(proto.Enum): @@ -404,6 +418,47 @@ class State(proto.Enum): DELETING = 4 UPDATING = 5 + class StreamingMode(proto.Enum): + r"""Streaming mode for a Gateway. + This enum is frozen. No values are expected to be added in the + future. + + Values: + STREAMING_MODE_UNSPECIFIED (0): + Lets the service select the streaming mode. + STREAMING_MODE_ENABLED (1): + Enables streaming. The gateway supports + Server-Sent Events (SSE), HTTP/2 streaming, HTTP + chunked transfer, WebSockets, and gRPC + bidirectional streaming. + """ + + STREAMING_MODE_UNSPECIFIED = 0 + STREAMING_MODE_ENABLED = 1 + + class EffectiveStreamingMode(proto.Enum): + r"""The streaming mode a Gateway is served with. + This enum is frozen. No values are expected to be added in the + future. + + Values: + EFFECTIVE_STREAMING_MODE_UNSPECIFIED (0): + Indicates that the service has not resolved a mode. Every + gateway returned by ``GetGateway`` and ``ListGateways`` + carries a resolved mode, so this value should not be + returned under normal circumstances. + EFFECTIVE_STREAMING_MODE_DISABLED (1): + Indicates that the gateway does not support + streaming. + EFFECTIVE_STREAMING_MODE_ENABLED (2): + Indicates that the gateway supports + streaming. + """ + + EFFECTIVE_STREAMING_MODE_UNSPECIFIED = 0 + EFFECTIVE_STREAMING_MODE_DISABLED = 1 + EFFECTIVE_STREAMING_MODE_ENABLED = 2 + name: str = proto.Field( proto.STRING, number=1, @@ -440,6 +495,16 @@ class State(proto.Enum): proto.STRING, number=9, ) + streaming_mode: StreamingMode = proto.Field( + proto.ENUM, + number=11, + enum=StreamingMode, + ) + effective_streaming_mode: EffectiveStreamingMode = proto.Field( + proto.ENUM, + number=12, + enum=EffectiveStreamingMode, + ) class ListGatewaysRequest(proto.Message): @@ -960,9 +1025,11 @@ class OperationMetadata(proto.Message): requested_cancellation (bool): Output only. Identifies whether the user has requested cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to ``Code.CANCELLED``. + successfully been cancelled have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. api_version (str): Output only. API version used to start the operation. diff --git a/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json b/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json index c74f3a9ce144..09eb8b43ede3 100644 --- a/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json +++ b/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-api-gateway", - "version": "1.16.0" + "version": "1.17.0" }, "snippets": [ { diff --git a/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py b/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py index eee21afe69da..723526db06e2 100644 --- a/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py +++ b/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py @@ -1650,6 +1650,8 @@ def test_get_gateway(request_type, transport: str = "grpc"): api_config="api_config_value", state=apigateway.Gateway.State.CREATING, default_hostname="default_hostname_value", + streaming_mode=apigateway.Gateway.StreamingMode.STREAMING_MODE_ENABLED, + effective_streaming_mode=apigateway.Gateway.EffectiveStreamingMode.EFFECTIVE_STREAMING_MODE_DISABLED, ) response = client.get_gateway(request) @@ -1666,6 +1668,14 @@ def test_get_gateway(request_type, transport: str = "grpc"): assert response.api_config == "api_config_value" assert response.state == apigateway.Gateway.State.CREATING assert response.default_hostname == "default_hostname_value" + assert ( + response.streaming_mode + == apigateway.Gateway.StreamingMode.STREAMING_MODE_ENABLED + ) + assert ( + response.effective_streaming_mode + == apigateway.Gateway.EffectiveStreamingMode.EFFECTIVE_STREAMING_MODE_DISABLED + ) def test_get_gateway_non_empty_request_with_auto_populated_field(): @@ -1802,6 +1812,8 @@ async def test_get_gateway_async(request_type, transport: str = "grpc_asyncio"): api_config="api_config_value", state=apigateway.Gateway.State.CREATING, default_hostname="default_hostname_value", + streaming_mode=apigateway.Gateway.StreamingMode.STREAMING_MODE_ENABLED, + effective_streaming_mode=apigateway.Gateway.EffectiveStreamingMode.EFFECTIVE_STREAMING_MODE_DISABLED, ) ) response = await client.get_gateway(request) @@ -1819,6 +1831,14 @@ async def test_get_gateway_async(request_type, transport: str = "grpc_asyncio"): assert response.api_config == "api_config_value" assert response.state == apigateway.Gateway.State.CREATING assert response.default_hostname == "default_hostname_value" + assert ( + response.streaming_mode + == apigateway.Gateway.StreamingMode.STREAMING_MODE_ENABLED + ) + assert ( + response.effective_streaming_mode + == apigateway.Gateway.EffectiveStreamingMode.EFFECTIVE_STREAMING_MODE_DISABLED + ) def test_get_gateway_field_headers(): @@ -10054,6 +10074,8 @@ async def test_get_gateway_empty_call_grpc_asyncio(): api_config="api_config_value", state=apigateway.Gateway.State.CREATING, default_hostname="default_hostname_value", + streaming_mode=apigateway.Gateway.StreamingMode.STREAMING_MODE_ENABLED, + effective_streaming_mode=apigateway.Gateway.EffectiveStreamingMode.EFFECTIVE_STREAMING_MODE_DISABLED, ) ) await client.get_gateway(request=None) @@ -10587,6 +10609,8 @@ def test_get_gateway_rest_call_success(request_type): api_config="api_config_value", state=apigateway.Gateway.State.CREATING, default_hostname="default_hostname_value", + streaming_mode=apigateway.Gateway.StreamingMode.STREAMING_MODE_ENABLED, + effective_streaming_mode=apigateway.Gateway.EffectiveStreamingMode.EFFECTIVE_STREAMING_MODE_DISABLED, ) # Wrap the value into a proper Response obj @@ -10608,6 +10632,14 @@ def test_get_gateway_rest_call_success(request_type): assert response.api_config == "api_config_value" assert response.state == apigateway.Gateway.State.CREATING assert response.default_hostname == "default_hostname_value" + assert ( + response.streaming_mode + == apigateway.Gateway.StreamingMode.STREAMING_MODE_ENABLED + ) + assert ( + response.effective_streaming_mode + == apigateway.Gateway.EffectiveStreamingMode.EFFECTIVE_STREAMING_MODE_DISABLED + ) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -10720,6 +10752,8 @@ def test_create_gateway_rest_call_success(request_type): "api_config": "api_config_value", "state": 1, "default_hostname": "default_hostname_value", + "streaming_mode": 1, + "effective_streaming_mode": 1, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -10925,6 +10959,8 @@ def test_update_gateway_rest_call_success(request_type): "api_config": "api_config_value", "state": 1, "default_hostname": "default_hostname_value", + "streaming_mode": 1, + "effective_streaming_mode": 1, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency diff --git a/packages/google-cloud-auditmanager/CHANGELOG.md b/packages/google-cloud-auditmanager/CHANGELOG.md index 2dde1d9a64a2..4a1989450bfe 100644 --- a/packages/google-cloud-auditmanager/CHANGELOG.md +++ b/packages/google-cloud-auditmanager/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-auditmanager/#history +## [0.3.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-auditmanager-v0.3.1...google-cloud-auditmanager-v0.3.2) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.3.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-auditmanager-v0.3.0...google-cloud-auditmanager-v0.3.1) (2026-08-21) diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py index a1274415ac6c..3115f3307815 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py @@ -26,20 +26,25 @@ ) from google.cloud.auditmanager_v1.types.auditmanager import ( AuditReport, + AuditSchedule, AuditScopeReport, ComplianceState, Control, ControlDetails, ControlFamily, + CreateAuditScheduleRequest, DestinationDetails, Enrollment, EnrollResourceRequest, GenerateAuditReportRequest, GenerateAuditScopeReportRequest, GetAuditReportRequest, + GetAuditScheduleRequest, GetResourceEnrollmentStatusRequest, ListAuditReportsRequest, ListAuditReportsResponse, + ListAuditSchedulesRequest, + ListAuditSchedulesResponse, ListControlsRequest, ListControlsResponse, ListResourceEnrollmentStatusesRequest, @@ -49,25 +54,33 @@ ReportGenerationProgress, ReportSummary, ResourceEnrollmentStatus, + ScheduleConfig, + ScheduleState, + UpdateAuditScheduleRequest, ) __all__ = ( "AuditManagerClient", "AuditManagerAsyncClient", "AuditReport", + "AuditSchedule", "AuditScopeReport", "Control", "ControlDetails", "ControlFamily", + "CreateAuditScheduleRequest", "DestinationDetails", "Enrollment", "EnrollResourceRequest", "GenerateAuditReportRequest", "GenerateAuditScopeReportRequest", "GetAuditReportRequest", + "GetAuditScheduleRequest", "GetResourceEnrollmentStatusRequest", "ListAuditReportsRequest", "ListAuditReportsResponse", + "ListAuditSchedulesRequest", + "ListAuditSchedulesResponse", "ListControlsRequest", "ListControlsResponse", "ListResourceEnrollmentStatusesRequest", @@ -76,6 +89,9 @@ "ReportGenerationProgress", "ReportSummary", "ResourceEnrollmentStatus", + "ScheduleConfig", + "UpdateAuditScheduleRequest", "ComplianceState", "OperationState", + "ScheduleState", ) diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager/gapic_version.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager/gapic_version.py index d88d0511755e..6fbb3bd7429b 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager/gapic_version.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.1" # {x-release-please-version} +__version__ = "0.3.2" # {x-release-please-version} diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py index 8370cd3c19e8..6ee06ad86de4 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py @@ -34,20 +34,25 @@ from .services.audit_manager import AuditManagerAsyncClient, AuditManagerClient from .types.auditmanager import ( AuditReport, + AuditSchedule, AuditScopeReport, ComplianceState, Control, ControlDetails, ControlFamily, + CreateAuditScheduleRequest, DestinationDetails, Enrollment, EnrollResourceRequest, GenerateAuditReportRequest, GenerateAuditScopeReportRequest, GetAuditReportRequest, + GetAuditScheduleRequest, GetResourceEnrollmentStatusRequest, ListAuditReportsRequest, ListAuditReportsResponse, + ListAuditSchedulesRequest, + ListAuditSchedulesResponse, ListControlsRequest, ListControlsResponse, ListResourceEnrollmentStatusesRequest, @@ -57,26 +62,34 @@ ReportGenerationProgress, ReportSummary, ResourceEnrollmentStatus, + ScheduleConfig, + ScheduleState, + UpdateAuditScheduleRequest, ) __all__ = ( "AuditManagerAsyncClient", "AuditManagerClient", "AuditReport", + "AuditSchedule", "AuditScopeReport", "ComplianceState", "Control", "ControlDetails", "ControlFamily", + "CreateAuditScheduleRequest", "DestinationDetails", "EnrollResourceRequest", "Enrollment", "GenerateAuditReportRequest", "GenerateAuditScopeReportRequest", "GetAuditReportRequest", + "GetAuditScheduleRequest", "GetResourceEnrollmentStatusRequest", "ListAuditReportsRequest", "ListAuditReportsResponse", + "ListAuditSchedulesRequest", + "ListAuditSchedulesResponse", "ListControlsRequest", "ListControlsResponse", "ListResourceEnrollmentStatusesRequest", @@ -86,6 +99,9 @@ "ReportGenerationProgress", "ReportSummary", "ResourceEnrollmentStatus", + "ScheduleConfig", + "ScheduleState", + "UpdateAuditScheduleRequest", ) api_core.check_python_version("google.cloud.auditmanager_v1") diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_metadata.json b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_metadata.json index d088d3acd92c..e8abb7229df1 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_metadata.json +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_metadata.json @@ -10,6 +10,11 @@ "grpc": { "libraryClient": "AuditManagerClient", "rpcs": { + "CreateAuditSchedule": { + "methods": [ + "create_audit_schedule" + ] + }, "EnrollResource": { "methods": [ "enroll_resource" @@ -30,6 +35,11 @@ "get_audit_report" ] }, + "GetAuditSchedule": { + "methods": [ + "get_audit_schedule" + ] + }, "GetResourceEnrollmentStatus": { "methods": [ "get_resource_enrollment_status" @@ -40,6 +50,11 @@ "list_audit_reports" ] }, + "ListAuditSchedules": { + "methods": [ + "list_audit_schedules" + ] + }, "ListControls": { "methods": [ "list_controls" @@ -49,12 +64,22 @@ "methods": [ "list_resource_enrollment_statuses" ] + }, + "UpdateAuditSchedule": { + "methods": [ + "update_audit_schedule" + ] } } }, "grpc-async": { "libraryClient": "AuditManagerAsyncClient", "rpcs": { + "CreateAuditSchedule": { + "methods": [ + "create_audit_schedule" + ] + }, "EnrollResource": { "methods": [ "enroll_resource" @@ -75,6 +100,11 @@ "get_audit_report" ] }, + "GetAuditSchedule": { + "methods": [ + "get_audit_schedule" + ] + }, "GetResourceEnrollmentStatus": { "methods": [ "get_resource_enrollment_status" @@ -85,6 +115,11 @@ "list_audit_reports" ] }, + "ListAuditSchedules": { + "methods": [ + "list_audit_schedules" + ] + }, "ListControls": { "methods": [ "list_controls" @@ -94,12 +129,22 @@ "methods": [ "list_resource_enrollment_statuses" ] + }, + "UpdateAuditSchedule": { + "methods": [ + "update_audit_schedule" + ] } } }, "rest": { "libraryClient": "AuditManagerClient", "rpcs": { + "CreateAuditSchedule": { + "methods": [ + "create_audit_schedule" + ] + }, "EnrollResource": { "methods": [ "enroll_resource" @@ -120,6 +165,11 @@ "get_audit_report" ] }, + "GetAuditSchedule": { + "methods": [ + "get_audit_schedule" + ] + }, "GetResourceEnrollmentStatus": { "methods": [ "get_resource_enrollment_status" @@ -130,6 +180,11 @@ "list_audit_reports" ] }, + "ListAuditSchedules": { + "methods": [ + "list_audit_schedules" + ] + }, "ListControls": { "methods": [ "list_controls" @@ -139,6 +194,11 @@ "methods": [ "list_resource_enrollment_statuses" ] + }, + "UpdateAuditSchedule": { + "methods": [ + "update_audit_schedule" + ] } } } diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_version.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_version.py index d88d0511755e..6fbb3bd7429b 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_version.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.1" # {x-release-please-version} +__version__ = "0.3.2" # {x-release-please-version} diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/async_client.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/async_client.py index 25f00d804bd8..9c4010801414 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/async_client.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/async_client.py @@ -46,6 +46,7 @@ import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore @@ -81,6 +82,10 @@ class AuditManagerAsyncClient: audit_report_path = staticmethod(AuditManagerClient.audit_report_path) parse_audit_report_path = staticmethod(AuditManagerClient.parse_audit_report_path) + audit_schedule_path = staticmethod(AuditManagerClient.audit_schedule_path) + parse_audit_schedule_path = staticmethod( + AuditManagerClient.parse_audit_schedule_path + ) audit_scope_report_path = staticmethod(AuditManagerClient.audit_scope_report_path) parse_audit_scope_report_path = staticmethod( AuditManagerClient.parse_audit_scope_report_path @@ -315,6 +320,526 @@ def __init__( }, ) + async def create_audit_schedule( + self, + request: Optional[Union[auditmanager.CreateAuditScheduleRequest, dict]] = None, + *, + parent: Optional[str] = None, + audit_schedule: Optional[auditmanager.AuditSchedule] = None, + audit_schedule_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Creates a new audit schedule in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + async def sample_create_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.CreateAuditScheduleRequest( + parent="parent_value", + audit_schedule=audit_schedule, + audit_schedule_id="audit_schedule_id_value", + ) + + # Make the request + response = await client.create_audit_schedule(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.auditmanager_v1.types.CreateAuditScheduleRequest, dict]]): + The request object. Request message for + [CreateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.CreateAuditSchedule]. + parent (:class:`str`): + Required. Project or folder that this audit schedule is + for, in one of the following formats: + + - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audit_schedule (:class:`google.cloud.auditmanager_v1.types.AuditSchedule`): + Required. Audit schedule to create. + This corresponds to the ``audit_schedule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audit_schedule_id (:class:`str`): + Required. ID to use for the audit + schedule, which becomes the final + component of the audit schedule's + resource name. + + This corresponds to the ``audit_schedule_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.types.AuditSchedule: + An audit schedule, in one of the following formats: + + - projects/{project}/locations/{location}/auditSchedules/{audit_schedule} + - folders/{folder}/locations/{location}/auditSchedules/{audit_schedule} + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, audit_schedule, audit_schedule_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.CreateAuditScheduleRequest): + request = auditmanager.CreateAuditScheduleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if audit_schedule is not None: + request.audit_schedule = audit_schedule + if audit_schedule_id is not None: + request.audit_schedule_id = audit_schedule_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_audit_schedule + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_audit_schedule( + self, + request: Optional[Union[auditmanager.UpdateAuditScheduleRequest, dict]] = None, + *, + audit_schedule: Optional[auditmanager.AuditSchedule] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Updates an existing audit schedule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + async def sample_update_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.UpdateAuditScheduleRequest( + audit_schedule=audit_schedule, + ) + + # Make the request + response = await client.update_audit_schedule(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.auditmanager_v1.types.UpdateAuditScheduleRequest, dict]]): + The request object. Request message for + [UpdateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.UpdateAuditSchedule]. + audit_schedule (:class:`google.cloud.auditmanager_v1.types.AuditSchedule`): + Required. Audit schedule to update. + This corresponds to the ``audit_schedule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.types.AuditSchedule: + An audit schedule, in one of the following formats: + + - projects/{project}/locations/{location}/auditSchedules/{audit_schedule} + - folders/{folder}/locations/{location}/auditSchedules/{audit_schedule} + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [audit_schedule, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.UpdateAuditScheduleRequest): + request = auditmanager.UpdateAuditScheduleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if audit_schedule is not None: + request.audit_schedule = audit_schedule + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_audit_schedule + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("audit_schedule.name", request.audit_schedule.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_audit_schedule( + self, + request: Optional[Union[auditmanager.GetAuditScheduleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Gets details of a single audit schedule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + async def sample_get_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + request = auditmanager_v1.GetAuditScheduleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_audit_schedule(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.auditmanager_v1.types.GetAuditScheduleRequest, dict]]): + The request object. Request message for + [GetAuditSchedule][google.cloud.auditmanager.v1.AuditManager.GetAuditSchedule]. + name (:class:`str`): + Required. Name of the audit schedule to retrieve, in one + of the following formats: + + - ``projects/{project}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``folders/{folder}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``organizations/{organization}/locations/{location}/auditSchedules/{audit_schedule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.types.AuditSchedule: + An audit schedule, in one of the following formats: + + - projects/{project}/locations/{location}/auditSchedules/{audit_schedule} + - folders/{folder}/locations/{location}/auditSchedules/{audit_schedule} + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.GetAuditScheduleRequest): + request = auditmanager.GetAuditScheduleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_audit_schedule + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_audit_schedules( + self, + request: Optional[Union[auditmanager.ListAuditSchedulesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAuditSchedulesAsyncPager: + r"""Lists audit schedules in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + async def sample_list_audit_schedules(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + request = auditmanager_v1.ListAuditSchedulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_audit_schedules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.auditmanager_v1.types.ListAuditSchedulesRequest, dict]]): + The request object. Request message for + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. + parent (:class:`str`): + Required. Parent for the audit schedule, in one of the + following formats: + + - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``organizations/{organization}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditSchedulesAsyncPager: + Response message for + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.ListAuditSchedulesRequest): + request = auditmanager.ListAuditSchedulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_audit_schedules + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAuditSchedulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def enroll_resource( self, request: Optional[Union[auditmanager.EnrollResourceRequest, dict]] = None, diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/client.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/client.py index c9cd95438641..c4620c5cd7e2 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/client.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/client.py @@ -70,6 +70,7 @@ import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore @@ -197,6 +198,28 @@ def parse_audit_report_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def audit_schedule_path( + project: str, + location: str, + audit_schedule: str, + ) -> str: + """Returns a fully-qualified audit_schedule string.""" + return "projects/{project}/locations/{location}/auditSchedules/{audit_schedule}".format( + project=project, + location=location, + audit_schedule=audit_schedule, + ) + + @staticmethod + def parse_audit_schedule_path(path: str) -> Dict[str, str]: + """Parses a audit_schedule path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/auditSchedules/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def audit_scope_report_path( project: str, @@ -703,6 +726,514 @@ def __init__( }, ) + def create_audit_schedule( + self, + request: Optional[Union[auditmanager.CreateAuditScheduleRequest, dict]] = None, + *, + parent: Optional[str] = None, + audit_schedule: Optional[auditmanager.AuditSchedule] = None, + audit_schedule_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Creates a new audit schedule in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + def sample_create_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.CreateAuditScheduleRequest( + parent="parent_value", + audit_schedule=audit_schedule, + audit_schedule_id="audit_schedule_id_value", + ) + + # Make the request + response = client.create_audit_schedule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.auditmanager_v1.types.CreateAuditScheduleRequest, dict]): + The request object. Request message for + [CreateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.CreateAuditSchedule]. + parent (str): + Required. Project or folder that this audit schedule is + for, in one of the following formats: + + - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audit_schedule (google.cloud.auditmanager_v1.types.AuditSchedule): + Required. Audit schedule to create. + This corresponds to the ``audit_schedule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audit_schedule_id (str): + Required. ID to use for the audit + schedule, which becomes the final + component of the audit schedule's + resource name. + + This corresponds to the ``audit_schedule_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.types.AuditSchedule: + An audit schedule, in one of the following formats: + + - projects/{project}/locations/{location}/auditSchedules/{audit_schedule} + - folders/{folder}/locations/{location}/auditSchedules/{audit_schedule} + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, audit_schedule, audit_schedule_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.CreateAuditScheduleRequest): + request = auditmanager.CreateAuditScheduleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if audit_schedule is not None: + request.audit_schedule = audit_schedule + if audit_schedule_id is not None: + request.audit_schedule_id = audit_schedule_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_audit_schedule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_audit_schedule( + self, + request: Optional[Union[auditmanager.UpdateAuditScheduleRequest, dict]] = None, + *, + audit_schedule: Optional[auditmanager.AuditSchedule] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Updates an existing audit schedule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + def sample_update_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.UpdateAuditScheduleRequest( + audit_schedule=audit_schedule, + ) + + # Make the request + response = client.update_audit_schedule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.auditmanager_v1.types.UpdateAuditScheduleRequest, dict]): + The request object. Request message for + [UpdateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.UpdateAuditSchedule]. + audit_schedule (google.cloud.auditmanager_v1.types.AuditSchedule): + Required. Audit schedule to update. + This corresponds to the ``audit_schedule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.types.AuditSchedule: + An audit schedule, in one of the following formats: + + - projects/{project}/locations/{location}/auditSchedules/{audit_schedule} + - folders/{folder}/locations/{location}/auditSchedules/{audit_schedule} + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [audit_schedule, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.UpdateAuditScheduleRequest): + request = auditmanager.UpdateAuditScheduleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if audit_schedule is not None: + request.audit_schedule = audit_schedule + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_audit_schedule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("audit_schedule.name", request.audit_schedule.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_audit_schedule( + self, + request: Optional[Union[auditmanager.GetAuditScheduleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Gets details of a single audit schedule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + def sample_get_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + request = auditmanager_v1.GetAuditScheduleRequest( + name="name_value", + ) + + # Make the request + response = client.get_audit_schedule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.auditmanager_v1.types.GetAuditScheduleRequest, dict]): + The request object. Request message for + [GetAuditSchedule][google.cloud.auditmanager.v1.AuditManager.GetAuditSchedule]. + name (str): + Required. Name of the audit schedule to retrieve, in one + of the following formats: + + - ``projects/{project}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``folders/{folder}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``organizations/{organization}/locations/{location}/auditSchedules/{audit_schedule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.types.AuditSchedule: + An audit schedule, in one of the following formats: + + - projects/{project}/locations/{location}/auditSchedules/{audit_schedule} + - folders/{folder}/locations/{location}/auditSchedules/{audit_schedule} + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.GetAuditScheduleRequest): + request = auditmanager.GetAuditScheduleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_audit_schedule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_audit_schedules( + self, + request: Optional[Union[auditmanager.ListAuditSchedulesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAuditSchedulesPager: + r"""Lists audit schedules in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import auditmanager_v1 + + def sample_list_audit_schedules(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + request = auditmanager_v1.ListAuditSchedulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_audit_schedules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.auditmanager_v1.types.ListAuditSchedulesRequest, dict]): + The request object. Request message for + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. + parent (str): + Required. Parent for the audit schedule, in one of the + following formats: + + - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``organizations/{organization}/locations/{location}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditSchedulesPager: + Response message for + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, auditmanager.ListAuditSchedulesRequest): + request = auditmanager.ListAuditSchedulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_audit_schedules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAuditSchedulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def enroll_resource( self, request: Optional[Union[auditmanager.EnrollResourceRequest, dict]] = None, diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/pagers.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/pagers.py index fa563e743d8c..01250da71451 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/pagers.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/pagers.py @@ -41,6 +41,162 @@ from google.cloud.auditmanager_v1.types import auditmanager +class ListAuditSchedulesPager: + """A pager for iterating through ``list_audit_schedules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.auditmanager_v1.types.ListAuditSchedulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``audit_schedules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAuditSchedules`` requests and continue to iterate + through the ``audit_schedules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.auditmanager_v1.types.ListAuditSchedulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., auditmanager.ListAuditSchedulesResponse], + request: auditmanager.ListAuditSchedulesRequest, + response: auditmanager.ListAuditSchedulesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.auditmanager_v1.types.ListAuditSchedulesRequest): + The initial request object. + response (google.cloud.auditmanager_v1.types.ListAuditSchedulesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = auditmanager.ListAuditSchedulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[auditmanager.ListAuditSchedulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[auditmanager.AuditSchedule]: + for page in self.pages: + yield from page.audit_schedules + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAuditSchedulesAsyncPager: + """A pager for iterating through ``list_audit_schedules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.auditmanager_v1.types.ListAuditSchedulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``audit_schedules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAuditSchedules`` requests and continue to iterate + through the ``audit_schedules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.auditmanager_v1.types.ListAuditSchedulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[auditmanager.ListAuditSchedulesResponse]], + request: auditmanager.ListAuditSchedulesRequest, + response: auditmanager.ListAuditSchedulesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.auditmanager_v1.types.ListAuditSchedulesRequest): + The initial request object. + response (google.cloud.auditmanager_v1.types.ListAuditSchedulesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = auditmanager.ListAuditSchedulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[auditmanager.ListAuditSchedulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[auditmanager.AuditSchedule]: + async def async_generator(): + async for page in self.pages: + for response in page.audit_schedules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListAuditReportsPager: """A pager for iterating through ``list_audit_reports`` requests. diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py index 5b070f4c31b6..303811f4c353 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py @@ -145,6 +145,35 @@ def host(self): def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { + self.create_audit_schedule: gapic_v1.method.wrap_method( + self.create_audit_schedule, + default_timeout=60.0, + client_info=client_info, + ), + self.update_audit_schedule: gapic_v1.method.wrap_method( + self.update_audit_schedule, + default_timeout=60.0, + client_info=client_info, + ), + self.get_audit_schedule: gapic_v1.method.wrap_method( + self.get_audit_schedule, + default_timeout=None, + client_info=client_info, + ), + self.list_audit_schedules: gapic_v1.method.wrap_method( + self.list_audit_schedules, + default_retry=retries.Retry( + initial=0.1, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.enroll_resource: gapic_v1.method.wrap_method( self.enroll_resource, default_timeout=60.0, @@ -276,6 +305,45 @@ def operations_client(self): """Return the client designed to process long-running operations.""" raise NotImplementedError() + @property + def create_audit_schedule( + self, + ) -> Callable[ + [auditmanager.CreateAuditScheduleRequest], + Union[auditmanager.AuditSchedule, Awaitable[auditmanager.AuditSchedule]], + ]: + raise NotImplementedError() + + @property + def update_audit_schedule( + self, + ) -> Callable[ + [auditmanager.UpdateAuditScheduleRequest], + Union[auditmanager.AuditSchedule, Awaitable[auditmanager.AuditSchedule]], + ]: + raise NotImplementedError() + + @property + def get_audit_schedule( + self, + ) -> Callable[ + [auditmanager.GetAuditScheduleRequest], + Union[auditmanager.AuditSchedule, Awaitable[auditmanager.AuditSchedule]], + ]: + raise NotImplementedError() + + @property + def list_audit_schedules( + self, + ) -> Callable[ + [auditmanager.ListAuditSchedulesRequest], + Union[ + auditmanager.ListAuditSchedulesResponse, + Awaitable[auditmanager.ListAuditSchedulesResponse], + ], + ]: + raise NotImplementedError() + @property def enroll_resource( self, diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc.py index 90ad27975ae6..c66b03869198 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc.py @@ -344,6 +344,119 @@ def operations_client(self) -> operations_v1.OperationsClient: # Return the client from cache. return self._operations_client + @property + def create_audit_schedule( + self, + ) -> Callable[ + [auditmanager.CreateAuditScheduleRequest], auditmanager.AuditSchedule + ]: + r"""Return a callable for the create audit schedule method over gRPC. + + Creates a new audit schedule in a given project and + location. + + Returns: + Callable[[~.CreateAuditScheduleRequest], + ~.AuditSchedule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_audit_schedule" not in self._stubs: + self._stubs["create_audit_schedule"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/CreateAuditSchedule", + request_serializer=auditmanager.CreateAuditScheduleRequest.serialize, + response_deserializer=auditmanager.AuditSchedule.deserialize, + ) + return self._stubs["create_audit_schedule"] + + @property + def update_audit_schedule( + self, + ) -> Callable[ + [auditmanager.UpdateAuditScheduleRequest], auditmanager.AuditSchedule + ]: + r"""Return a callable for the update audit schedule method over gRPC. + + Updates an existing audit schedule. + + Returns: + Callable[[~.UpdateAuditScheduleRequest], + ~.AuditSchedule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_audit_schedule" not in self._stubs: + self._stubs["update_audit_schedule"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/UpdateAuditSchedule", + request_serializer=auditmanager.UpdateAuditScheduleRequest.serialize, + response_deserializer=auditmanager.AuditSchedule.deserialize, + ) + return self._stubs["update_audit_schedule"] + + @property + def get_audit_schedule( + self, + ) -> Callable[[auditmanager.GetAuditScheduleRequest], auditmanager.AuditSchedule]: + r"""Return a callable for the get audit schedule method over gRPC. + + Gets details of a single audit schedule. + + Returns: + Callable[[~.GetAuditScheduleRequest], + ~.AuditSchedule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_audit_schedule" not in self._stubs: + self._stubs["get_audit_schedule"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/GetAuditSchedule", + request_serializer=auditmanager.GetAuditScheduleRequest.serialize, + response_deserializer=auditmanager.AuditSchedule.deserialize, + ) + return self._stubs["get_audit_schedule"] + + @property + def list_audit_schedules( + self, + ) -> Callable[ + [auditmanager.ListAuditSchedulesRequest], + auditmanager.ListAuditSchedulesResponse, + ]: + r"""Return a callable for the list audit schedules method over gRPC. + + Lists audit schedules in a given project and + location. + + Returns: + Callable[[~.ListAuditSchedulesRequest], + ~.ListAuditSchedulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_audit_schedules" not in self._stubs: + self._stubs["list_audit_schedules"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/ListAuditSchedules", + request_serializer=auditmanager.ListAuditSchedulesRequest.serialize, + response_deserializer=auditmanager.ListAuditSchedulesResponse.deserialize, + ) + return self._stubs["list_audit_schedules"] + @property def enroll_resource( self, diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py index 17e817e13657..58e6f92a78df 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py @@ -352,6 +352,121 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: # Return the client from cache. return self._operations_client + @property + def create_audit_schedule( + self, + ) -> Callable[ + [auditmanager.CreateAuditScheduleRequest], Awaitable[auditmanager.AuditSchedule] + ]: + r"""Return a callable for the create audit schedule method over gRPC. + + Creates a new audit schedule in a given project and + location. + + Returns: + Callable[[~.CreateAuditScheduleRequest], + Awaitable[~.AuditSchedule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_audit_schedule" not in self._stubs: + self._stubs["create_audit_schedule"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/CreateAuditSchedule", + request_serializer=auditmanager.CreateAuditScheduleRequest.serialize, + response_deserializer=auditmanager.AuditSchedule.deserialize, + ) + return self._stubs["create_audit_schedule"] + + @property + def update_audit_schedule( + self, + ) -> Callable[ + [auditmanager.UpdateAuditScheduleRequest], Awaitable[auditmanager.AuditSchedule] + ]: + r"""Return a callable for the update audit schedule method over gRPC. + + Updates an existing audit schedule. + + Returns: + Callable[[~.UpdateAuditScheduleRequest], + Awaitable[~.AuditSchedule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_audit_schedule" not in self._stubs: + self._stubs["update_audit_schedule"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/UpdateAuditSchedule", + request_serializer=auditmanager.UpdateAuditScheduleRequest.serialize, + response_deserializer=auditmanager.AuditSchedule.deserialize, + ) + return self._stubs["update_audit_schedule"] + + @property + def get_audit_schedule( + self, + ) -> Callable[ + [auditmanager.GetAuditScheduleRequest], Awaitable[auditmanager.AuditSchedule] + ]: + r"""Return a callable for the get audit schedule method over gRPC. + + Gets details of a single audit schedule. + + Returns: + Callable[[~.GetAuditScheduleRequest], + Awaitable[~.AuditSchedule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_audit_schedule" not in self._stubs: + self._stubs["get_audit_schedule"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/GetAuditSchedule", + request_serializer=auditmanager.GetAuditScheduleRequest.serialize, + response_deserializer=auditmanager.AuditSchedule.deserialize, + ) + return self._stubs["get_audit_schedule"] + + @property + def list_audit_schedules( + self, + ) -> Callable[ + [auditmanager.ListAuditSchedulesRequest], + Awaitable[auditmanager.ListAuditSchedulesResponse], + ]: + r"""Return a callable for the list audit schedules method over gRPC. + + Lists audit schedules in a given project and + location. + + Returns: + Callable[[~.ListAuditSchedulesRequest], + Awaitable[~.ListAuditSchedulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_audit_schedules" not in self._stubs: + self._stubs["list_audit_schedules"] = self._logged_channel.unary_unary( + "/google.cloud.auditmanager.v1.AuditManager/ListAuditSchedules", + request_serializer=auditmanager.ListAuditSchedulesRequest.serialize, + response_deserializer=auditmanager.ListAuditSchedulesResponse.deserialize, + ) + return self._stubs["list_audit_schedules"] + @property def enroll_resource( self, @@ -608,6 +723,35 @@ def list_controls( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { + self.create_audit_schedule: self._wrap_method( + self.create_audit_schedule, + default_timeout=60.0, + client_info=client_info, + ), + self.update_audit_schedule: self._wrap_method( + self.update_audit_schedule, + default_timeout=60.0, + client_info=client_info, + ), + self.get_audit_schedule: self._wrap_method( + self.get_audit_schedule, + default_timeout=None, + client_info=client_info, + ), + self.list_audit_schedules: self._wrap_method( + self.list_audit_schedules, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.enroll_resource: self._wrap_method( self.enroll_resource, default_timeout=60.0, diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest.py index 3f259b1bd360..6a0add0283f4 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest.py @@ -74,6 +74,14 @@ class AuditManagerRestInterceptor: .. code-block:: python class MyCustomAuditManagerInterceptor(AuditManagerRestInterceptor): + def pre_create_audit_schedule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_audit_schedule(self, response): + logging.log(f"Received response: {response}") + return response + def pre_enroll_resource(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -106,6 +114,14 @@ def post_get_audit_report(self, response): logging.log(f"Received response: {response}") return response + def pre_get_audit_schedule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_audit_schedule(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_resource_enrollment_status(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -122,6 +138,14 @@ def post_list_audit_reports(self, response): logging.log(f"Received response: {response}") return response + def pre_list_audit_schedules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_audit_schedules(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_controls(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -138,12 +162,68 @@ def post_list_resource_enrollment_statuses(self, response): logging.log(f"Received response: {response}") return response + def pre_update_audit_schedule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_audit_schedule(self, response): + logging.log(f"Received response: {response}") + return response + transport = AuditManagerRestTransport(interceptor=MyCustomAuditManagerInterceptor()) client = AuditManagerClient(transport=transport) """ + def pre_create_audit_schedule( + self, + request: auditmanager.CreateAuditScheduleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + auditmanager.CreateAuditScheduleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_audit_schedule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AuditManager server. + """ + return request, metadata + + def post_create_audit_schedule( + self, response: auditmanager.AuditSchedule + ) -> auditmanager.AuditSchedule: + """Post-rpc interceptor for create_audit_schedule + + DEPRECATED. Please use the `post_create_audit_schedule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AuditManager server but before + it is returned to user code. This `post_create_audit_schedule` interceptor runs + before the `post_create_audit_schedule_with_metadata` interceptor. + """ + return response + + def post_create_audit_schedule_with_metadata( + self, + response: auditmanager.AuditSchedule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[auditmanager.AuditSchedule, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_audit_schedule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AuditManager server but before it is returned to user code. + + We recommend only using this `post_create_audit_schedule_with_metadata` + interceptor in new development instead of the `post_create_audit_schedule` interceptor. + When both interceptors are used, this `post_create_audit_schedule_with_metadata` interceptor runs after the + `post_create_audit_schedule` interceptor. The (possibly modified) response returned by + `post_create_audit_schedule` will be passed to + `post_create_audit_schedule_with_metadata`. + """ + return response, metadata + def pre_enroll_resource( self, request: auditmanager.EnrollResourceRequest, @@ -337,6 +417,54 @@ def post_get_audit_report_with_metadata( """ return response, metadata + def pre_get_audit_schedule( + self, + request: auditmanager.GetAuditScheduleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + auditmanager.GetAuditScheduleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_audit_schedule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AuditManager server. + """ + return request, metadata + + def post_get_audit_schedule( + self, response: auditmanager.AuditSchedule + ) -> auditmanager.AuditSchedule: + """Post-rpc interceptor for get_audit_schedule + + DEPRECATED. Please use the `post_get_audit_schedule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AuditManager server but before + it is returned to user code. This `post_get_audit_schedule` interceptor runs + before the `post_get_audit_schedule_with_metadata` interceptor. + """ + return response + + def post_get_audit_schedule_with_metadata( + self, + response: auditmanager.AuditSchedule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[auditmanager.AuditSchedule, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_audit_schedule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AuditManager server but before it is returned to user code. + + We recommend only using this `post_get_audit_schedule_with_metadata` + interceptor in new development instead of the `post_get_audit_schedule` interceptor. + When both interceptors are used, this `post_get_audit_schedule_with_metadata` interceptor runs after the + `post_get_audit_schedule` interceptor. The (possibly modified) response returned by + `post_get_audit_schedule` will be passed to + `post_get_audit_schedule_with_metadata`. + """ + return response, metadata + def pre_get_resource_enrollment_status( self, request: auditmanager.GetResourceEnrollmentStatusRequest, @@ -438,6 +566,56 @@ def post_list_audit_reports_with_metadata( """ return response, metadata + def pre_list_audit_schedules( + self, + request: auditmanager.ListAuditSchedulesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + auditmanager.ListAuditSchedulesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_audit_schedules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AuditManager server. + """ + return request, metadata + + def post_list_audit_schedules( + self, response: auditmanager.ListAuditSchedulesResponse + ) -> auditmanager.ListAuditSchedulesResponse: + """Post-rpc interceptor for list_audit_schedules + + DEPRECATED. Please use the `post_list_audit_schedules_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AuditManager server but before + it is returned to user code. This `post_list_audit_schedules` interceptor runs + before the `post_list_audit_schedules_with_metadata` interceptor. + """ + return response + + def post_list_audit_schedules_with_metadata( + self, + response: auditmanager.ListAuditSchedulesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + auditmanager.ListAuditSchedulesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_audit_schedules + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AuditManager server but before it is returned to user code. + + We recommend only using this `post_list_audit_schedules_with_metadata` + interceptor in new development instead of the `post_list_audit_schedules` interceptor. + When both interceptors are used, this `post_list_audit_schedules_with_metadata` interceptor runs after the + `post_list_audit_schedules` interceptor. The (possibly modified) response returned by + `post_list_audit_schedules` will be passed to + `post_list_audit_schedules_with_metadata`. + """ + return response, metadata + def pre_list_controls( self, request: auditmanager.ListControlsRequest, @@ -540,6 +718,54 @@ def post_list_resource_enrollment_statuses_with_metadata( """ return response, metadata + def pre_update_audit_schedule( + self, + request: auditmanager.UpdateAuditScheduleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + auditmanager.UpdateAuditScheduleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_audit_schedule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AuditManager server. + """ + return request, metadata + + def post_update_audit_schedule( + self, response: auditmanager.AuditSchedule + ) -> auditmanager.AuditSchedule: + """Post-rpc interceptor for update_audit_schedule + + DEPRECATED. Please use the `post_update_audit_schedule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AuditManager server but before + it is returned to user code. This `post_update_audit_schedule` interceptor runs + before the `post_update_audit_schedule_with_metadata` interceptor. + """ + return response + + def post_update_audit_schedule_with_metadata( + self, + response: auditmanager.AuditSchedule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[auditmanager.AuditSchedule, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_audit_schedule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AuditManager server but before it is returned to user code. + + We recommend only using this `post_update_audit_schedule_with_metadata` + interceptor in new development instead of the `post_update_audit_schedule` interceptor. + When both interceptors are used, this `post_update_audit_schedule_with_metadata` interceptor runs after the + `post_update_audit_schedule` interceptor. The (possibly modified) response returned by + `post_update_audit_schedule` will be passed to + `post_update_audit_schedule_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -851,11 +1077,11 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _EnrollResource( - _BaseAuditManagerRestTransport._BaseEnrollResource, AuditManagerRestStub + class _CreateAuditSchedule( + _BaseAuditManagerRestTransport._BaseCreateAuditSchedule, AuditManagerRestStub ): def __hash__(self): - return hash("AuditManagerRestTransport.EnrollResource") + return hash("AuditManagerRestTransport.CreateAuditSchedule") @staticmethod def _get_response( @@ -882,18 +1108,18 @@ def _get_response( def __call__( self, - request: auditmanager.EnrollResourceRequest, + request: auditmanager.CreateAuditScheduleRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> auditmanager.Enrollment: - r"""Call the enroll resource method over HTTP. + ) -> auditmanager.AuditSchedule: + r"""Call the create audit schedule method over HTTP. Args: - request (~.auditmanager.EnrollResourceRequest): + request (~.auditmanager.CreateAuditScheduleRequest): The request object. Request message for - [EnrollResource][google.cloud.auditmanager.v1.AuditManager.EnrollResource]. + [CreateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.CreateAuditSchedule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -903,22 +1129,24 @@ def __call__( be of type `bytes`. Returns: - ~.auditmanager.Enrollment: - Organization, folder, or project to - enroll for audit reports. + ~.auditmanager.AuditSchedule: + An audit schedule, in one of the following formats: + + - ``projects/{project}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``folders/{folder}/locations/{location}/auditSchedules/{audit_schedule}`` """ - http_options = ( - _BaseAuditManagerRestTransport._BaseEnrollResource._get_http_options() + http_options = _BaseAuditManagerRestTransport._BaseCreateAuditSchedule._get_http_options() + request, metadata = self._interceptor.pre_create_audit_schedule( + request, metadata ) - request, metadata = self._interceptor.pre_enroll_resource(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseAuditManagerRestTransport._BaseEnrollResource, - "_BaseEnrollResource__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseAuditManagerRestTransport._BaseCreateAuditSchedule, + "_BaseCreateAuditSchedule__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -942,17 +1170,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.EnrollResource", + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.CreateAuditSchedule", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "EnrollResource", + "rpcName": "CreateAuditSchedule", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = AuditManagerRestTransport._EnrollResource._get_response( + response = AuditManagerRestTransport._CreateAuditSchedule._get_response( self._host, metadata, query_params, @@ -968,21 +1196,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = auditmanager.Enrollment() - pb_resp = auditmanager.Enrollment.pb(resp) + resp = auditmanager.AuditSchedule() + pb_resp = auditmanager.AuditSchedule.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_enroll_resource(resp) + resp = self._interceptor.post_create_audit_schedule(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_enroll_resource_with_metadata( + resp, _ = self._interceptor.post_create_audit_schedule_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = auditmanager.Enrollment.to_json(response) + response_payload = auditmanager.AuditSchedule.to_json(response) except: response_payload = None http_response = { @@ -991,21 +1219,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.auditmanager_v1.AuditManagerClient.enroll_resource", + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.create_audit_schedule", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "EnrollResource", + "rpcName": "CreateAuditSchedule", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GenerateAuditReport( - _BaseAuditManagerRestTransport._BaseGenerateAuditReport, AuditManagerRestStub + class _EnrollResource( + _BaseAuditManagerRestTransport._BaseEnrollResource, AuditManagerRestStub ): def __hash__(self): - return hash("AuditManagerRestTransport.GenerateAuditReport") + return hash("AuditManagerRestTransport.EnrollResource") @staticmethod def _get_response( @@ -1032,18 +1260,18 @@ def _get_response( def __call__( self, - request: auditmanager.GenerateAuditReportRequest, + request: auditmanager.EnrollResourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the generate audit report method over HTTP. + ) -> auditmanager.Enrollment: + r"""Call the enroll resource method over HTTP. Args: - request (~.auditmanager.GenerateAuditReportRequest): + request (~.auditmanager.EnrollResourceRequest): The request object. Request message for - [GenerateAuditReport][google.cloud.auditmanager.v1.AuditManager.GenerateAuditReport]. + [EnrollResource][google.cloud.auditmanager.v1.AuditManager.EnrollResource]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1053,23 +1281,22 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.auditmanager.Enrollment: + Organization, folder, or project to + enroll for audit reports. """ - http_options = _BaseAuditManagerRestTransport._BaseGenerateAuditReport._get_http_options() - request, metadata = self._interceptor.pre_generate_audit_report( - request, metadata + http_options = ( + _BaseAuditManagerRestTransport._BaseEnrollResource._get_http_options() ) + request, metadata = self._interceptor.pre_enroll_resource(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseAuditManagerRestTransport._BaseGenerateAuditReport, - "_BaseGenerateAuditReport__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseAuditManagerRestTransport._BaseEnrollResource, + "_BaseEnrollResource__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1093,17 +1320,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.GenerateAuditReport", + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.EnrollResource", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "GenerateAuditReport", + "rpcName": "EnrollResource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = AuditManagerRestTransport._GenerateAuditReport._get_response( + response = AuditManagerRestTransport._EnrollResource._get_response( self._host, metadata, query_params, @@ -1119,19 +1346,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = auditmanager.Enrollment() + pb_resp = auditmanager.Enrollment.pb(resp) - resp = self._interceptor.post_generate_audit_report(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_enroll_resource(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_audit_report_with_metadata( + resp, _ = self._interceptor.post_enroll_resource_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = auditmanager.Enrollment.to_json(response) except: response_payload = None http_response = { @@ -1140,22 +1369,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.auditmanager_v1.AuditManagerClient.generate_audit_report", + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.enroll_resource", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "GenerateAuditReport", + "rpcName": "EnrollResource", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GenerateAuditScopeReport( - _BaseAuditManagerRestTransport._BaseGenerateAuditScopeReport, - AuditManagerRestStub, + class _GenerateAuditReport( + _BaseAuditManagerRestTransport._BaseGenerateAuditReport, AuditManagerRestStub ): def __hash__(self): - return hash("AuditManagerRestTransport.GenerateAuditScopeReport") + return hash("AuditManagerRestTransport.GenerateAuditReport") @staticmethod def _get_response( @@ -1182,30 +1410,180 @@ def _get_response( def __call__( self, - request: auditmanager.GenerateAuditScopeReportRequest, + request: auditmanager.GenerateAuditReportRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> auditmanager.AuditScopeReport: - r"""Call the generate audit scope - report method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the generate audit report method over HTTP. - Args: - request (~.auditmanager.GenerateAuditScopeReportRequest): - The request object. Request message for - [GenerateAuditScopeReport][google.cloud.auditmanager.v1.AuditManager.GenerateAuditScopeReport]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.auditmanager.GenerateAuditReportRequest): + The request object. Request message for + [GenerateAuditReport][google.cloud.auditmanager.v1.AuditManager.GenerateAuditReport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. - Returns: - ~.auditmanager.AuditScopeReport: - Audit scope report. + """ + + http_options = _BaseAuditManagerRestTransport._BaseGenerateAuditReport._get_http_options() + request, metadata = self._interceptor.pre_generate_audit_report( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAuditManagerRestTransport._BaseGenerateAuditReport, + "_BaseGenerateAuditReport__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.GenerateAuditReport", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "GenerateAuditReport", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AuditManagerRestTransport._GenerateAuditReport._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_audit_report(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_generate_audit_report_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.generate_audit_report", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "GenerateAuditReport", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAuditScopeReport( + _BaseAuditManagerRestTransport._BaseGenerateAuditScopeReport, + AuditManagerRestStub, + ): + def __hash__(self): + return hash("AuditManagerRestTransport.GenerateAuditScopeReport") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: auditmanager.GenerateAuditScopeReportRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditScopeReport: + r"""Call the generate audit scope + report method over HTTP. + + Args: + request (~.auditmanager.GenerateAuditScopeReportRequest): + The request object. Request message for + [GenerateAuditScopeReport][google.cloud.auditmanager.v1.AuditManager.GenerateAuditScopeReport]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.auditmanager.AuditScopeReport: + Audit scope report. """ http_options = _BaseAuditManagerRestTransport._BaseGenerateAuditScopeReport._get_http_options() @@ -1450,6 +1828,158 @@ def __call__( ) return resp + class _GetAuditSchedule( + _BaseAuditManagerRestTransport._BaseGetAuditSchedule, AuditManagerRestStub + ): + def __hash__(self): + return hash("AuditManagerRestTransport.GetAuditSchedule") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: auditmanager.GetAuditScheduleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Call the get audit schedule method over HTTP. + + Args: + request (~.auditmanager.GetAuditScheduleRequest): + The request object. Request message for + [GetAuditSchedule][google.cloud.auditmanager.v1.AuditManager.GetAuditSchedule]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.auditmanager.AuditSchedule: + An audit schedule, in one of the following formats: + + - ``projects/{project}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``folders/{folder}/locations/{location}/auditSchedules/{audit_schedule}`` + + """ + + http_options = ( + _BaseAuditManagerRestTransport._BaseGetAuditSchedule._get_http_options() + ) + request, metadata = self._interceptor.pre_get_audit_schedule( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAuditManagerRestTransport._BaseGetAuditSchedule, + "_BaseGetAuditSchedule__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.GetAuditSchedule", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "GetAuditSchedule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AuditManagerRestTransport._GetAuditSchedule._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = auditmanager.AuditSchedule() + pb_resp = auditmanager.AuditSchedule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_audit_schedule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_audit_schedule_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = auditmanager.AuditSchedule.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.get_audit_schedule", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "GetAuditSchedule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetResourceEnrollmentStatus( _BaseAuditManagerRestTransport._BaseGetResourceEnrollmentStatus, AuditManagerRestStub, @@ -1490,35 +2020,191 @@ def __call__( r"""Call the get resource enrollment status method over HTTP. - Args: - request (~.auditmanager.GetResourceEnrollmentStatusRequest): - The request object. Request message for - [GetResourceEnrollmentStatus][google.cloud.auditmanager.v1.AuditManager.GetResourceEnrollmentStatus]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.auditmanager.GetResourceEnrollmentStatusRequest): + The request object. Request message for + [GetResourceEnrollmentStatus][google.cloud.auditmanager.v1.AuditManager.GetResourceEnrollmentStatus]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.auditmanager.ResourceEnrollmentStatus: + An organization, folder, or project + with its enrollment status. + + """ + + http_options = _BaseAuditManagerRestTransport._BaseGetResourceEnrollmentStatus._get_http_options() + request, metadata = self._interceptor.pre_get_resource_enrollment_status( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAuditManagerRestTransport._BaseGetResourceEnrollmentStatus, + "_BaseGetResourceEnrollmentStatus__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.GetResourceEnrollmentStatus", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "GetResourceEnrollmentStatus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + AuditManagerRestTransport._GetResourceEnrollmentStatus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = auditmanager.ResourceEnrollmentStatus() + pb_resp = auditmanager.ResourceEnrollmentStatus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_resource_enrollment_status(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_resource_enrollment_status_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = auditmanager.ResourceEnrollmentStatus.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.get_resource_enrollment_status", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "GetResourceEnrollmentStatus", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAuditReports( + _BaseAuditManagerRestTransport._BaseListAuditReports, AuditManagerRestStub + ): + def __hash__(self): + return hash("AuditManagerRestTransport.ListAuditReports") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: auditmanager.ListAuditReportsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.ListAuditReportsResponse: + r"""Call the list audit reports method over HTTP. + + Args: + request (~.auditmanager.ListAuditReportsRequest): + The request object. Request message for + [ListAuditReports][google.cloud.auditmanager.v1.AuditManager.ListAuditReports]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. - Returns: - ~.auditmanager.ResourceEnrollmentStatus: - An organization, folder, or project - with its enrollment status. + Returns: + ~.auditmanager.ListAuditReportsResponse: + Response message for + [ListAuditReports][google.cloud.auditmanager.v1.AuditManager.ListAuditReports]. """ - http_options = _BaseAuditManagerRestTransport._BaseGetResourceEnrollmentStatus._get_http_options() - request, metadata = self._interceptor.pre_get_resource_enrollment_status( + http_options = ( + _BaseAuditManagerRestTransport._BaseListAuditReports._get_http_options() + ) + request, metadata = self._interceptor.pre_list_audit_reports( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseAuditManagerRestTransport._BaseGetResourceEnrollmentStatus, - "_BaseGetResourceEnrollmentStatus__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseAuditManagerRestTransport._BaseListAuditReports, + "_BaseListAuditReports__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1542,25 +2228,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.GetResourceEnrollmentStatus", + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.ListAuditReports", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "GetResourceEnrollmentStatus", + "rpcName": "ListAuditReports", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - AuditManagerRestTransport._GetResourceEnrollmentStatus._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = AuditManagerRestTransport._ListAuditReports._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1569,23 +2253,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = auditmanager.ResourceEnrollmentStatus() - pb_resp = auditmanager.ResourceEnrollmentStatus.pb(resp) + resp = auditmanager.ListAuditReportsResponse() + pb_resp = auditmanager.ListAuditReportsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_resource_enrollment_status(resp) + resp = self._interceptor.post_list_audit_reports(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_get_resource_enrollment_status_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_list_audit_reports_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = auditmanager.ResourceEnrollmentStatus.to_json( + response_payload = auditmanager.ListAuditReportsResponse.to_json( response ) except: @@ -1596,21 +2278,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.auditmanager_v1.AuditManagerClient.get_resource_enrollment_status", + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.list_audit_reports", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "GetResourceEnrollmentStatus", + "rpcName": "ListAuditReports", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAuditReports( - _BaseAuditManagerRestTransport._BaseListAuditReports, AuditManagerRestStub + class _ListAuditSchedules( + _BaseAuditManagerRestTransport._BaseListAuditSchedules, AuditManagerRestStub ): def __hash__(self): - return hash("AuditManagerRestTransport.ListAuditReports") + return hash("AuditManagerRestTransport.ListAuditSchedules") @staticmethod def _get_response( @@ -1636,18 +2318,18 @@ def _get_response( def __call__( self, - request: auditmanager.ListAuditReportsRequest, + request: auditmanager.ListAuditSchedulesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> auditmanager.ListAuditReportsResponse: - r"""Call the list audit reports method over HTTP. + ) -> auditmanager.ListAuditSchedulesResponse: + r"""Call the list audit schedules method over HTTP. Args: - request (~.auditmanager.ListAuditReportsRequest): + request (~.auditmanager.ListAuditSchedulesRequest): The request object. Request message for - [ListAuditReports][google.cloud.auditmanager.v1.AuditManager.ListAuditReports]. + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1657,24 +2339,22 @@ def __call__( be of type `bytes`. Returns: - ~.auditmanager.ListAuditReportsResponse: + ~.auditmanager.ListAuditSchedulesResponse: Response message for - [ListAuditReports][google.cloud.auditmanager.v1.AuditManager.ListAuditReports]. + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. """ - http_options = ( - _BaseAuditManagerRestTransport._BaseListAuditReports._get_http_options() - ) - request, metadata = self._interceptor.pre_list_audit_reports( + http_options = _BaseAuditManagerRestTransport._BaseListAuditSchedules._get_http_options() + request, metadata = self._interceptor.pre_list_audit_schedules( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseAuditManagerRestTransport._BaseListAuditReports, - "_BaseListAuditReports__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseAuditManagerRestTransport._BaseListAuditSchedules, + "_BaseListAuditSchedules__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1698,17 +2378,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.ListAuditReports", + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.ListAuditSchedules", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "ListAuditReports", + "rpcName": "ListAuditSchedules", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = AuditManagerRestTransport._ListAuditReports._get_response( + response = AuditManagerRestTransport._ListAuditSchedules._get_response( self._host, metadata, query_params, @@ -1723,21 +2403,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = auditmanager.ListAuditReportsResponse() - pb_resp = auditmanager.ListAuditReportsResponse.pb(resp) + resp = auditmanager.ListAuditSchedulesResponse() + pb_resp = auditmanager.ListAuditSchedulesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_audit_reports(resp) + resp = self._interceptor.post_list_audit_schedules(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_audit_reports_with_metadata( + resp, _ = self._interceptor.post_list_audit_schedules_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = auditmanager.ListAuditReportsResponse.to_json( + response_payload = auditmanager.ListAuditSchedulesResponse.to_json( response ) except: @@ -1748,10 +2428,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.auditmanager_v1.AuditManagerClient.list_audit_reports", + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.list_audit_schedules", extra={ "serviceName": "google.cloud.auditmanager.v1.AuditManager", - "rpcName": "ListAuditReports", + "rpcName": "ListAuditSchedules", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -2066,6 +2746,168 @@ def __call__( ) return resp + class _UpdateAuditSchedule( + _BaseAuditManagerRestTransport._BaseUpdateAuditSchedule, AuditManagerRestStub + ): + def __hash__(self): + return hash("AuditManagerRestTransport.UpdateAuditSchedule") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: auditmanager.UpdateAuditScheduleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> auditmanager.AuditSchedule: + r"""Call the update audit schedule method over HTTP. + + Args: + request (~.auditmanager.UpdateAuditScheduleRequest): + The request object. Request message for + [UpdateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.UpdateAuditSchedule]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.auditmanager.AuditSchedule: + An audit schedule, in one of the following formats: + + - ``projects/{project}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``folders/{folder}/locations/{location}/auditSchedules/{audit_schedule}`` + + """ + + http_options = _BaseAuditManagerRestTransport._BaseUpdateAuditSchedule._get_http_options() + request, metadata = self._interceptor.pre_update_audit_schedule( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAuditManagerRestTransport._BaseUpdateAuditSchedule, + "_BaseUpdateAuditSchedule__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.auditmanager_v1.AuditManagerClient.UpdateAuditSchedule", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "UpdateAuditSchedule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AuditManagerRestTransport._UpdateAuditSchedule._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = auditmanager.AuditSchedule() + pb_resp = auditmanager.AuditSchedule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_audit_schedule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_audit_schedule_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = auditmanager.AuditSchedule.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.auditmanager_v1.AuditManagerClient.update_audit_schedule", + extra={ + "serviceName": "google.cloud.auditmanager.v1.AuditManager", + "rpcName": "UpdateAuditSchedule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_audit_schedule( + self, + ) -> Callable[ + [auditmanager.CreateAuditScheduleRequest], auditmanager.AuditSchedule + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAuditSchedule(self._session, self._host, self._interceptor) # type: ignore + @property def enroll_resource( self, @@ -2102,6 +2944,14 @@ def get_audit_report( # In C++ this would require a dynamic_cast return self._GetAuditReport(self._session, self._host, self._interceptor) # type: ignore + @property + def get_audit_schedule( + self, + ) -> Callable[[auditmanager.GetAuditScheduleRequest], auditmanager.AuditSchedule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAuditSchedule(self._session, self._host, self._interceptor) # type: ignore + @property def get_resource_enrollment_status( self, @@ -2125,6 +2975,17 @@ def list_audit_reports( # In C++ this would require a dynamic_cast return self._ListAuditReports(self._session, self._host, self._interceptor) # type: ignore + @property + def list_audit_schedules( + self, + ) -> Callable[ + [auditmanager.ListAuditSchedulesRequest], + auditmanager.ListAuditSchedulesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAuditSchedules(self._session, self._host, self._interceptor) # type: ignore + @property def list_controls( self, @@ -2148,6 +3009,16 @@ def list_resource_enrollment_statuses( self._session, self._host, self._interceptor ) # type: ignore + @property + def update_audit_schedule( + self, + ) -> Callable[ + [auditmanager.UpdateAuditScheduleRequest], auditmanager.AuditSchedule + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAuditSchedule(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest_base.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest_base.py index 9dfb19db64e2..9115fc7d2476 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest_base.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/rest_base.py @@ -89,6 +89,35 @@ def __init__( api_audience=api_audience, ) + class _BaseCreateAuditSchedule: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "auditScheduleId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/auditSchedules", + "body": "audit_schedule", + }, + { + "method": "post", + "uri": "/v1/{parent=folders/*/locations/*}/auditSchedules", + "body": "audit_schedule", + }, + { + "method": "post", + "uri": "/v1/{parent=organizations/*/locations/*}/auditSchedules", + "body": "audit_schedule", + }, + ] + return http_options + class _BaseEnrollResource: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -194,6 +223,30 @@ def _get_http_options(): ] return http_options + class _BaseGetAuditSchedule: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/auditSchedules/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/auditSchedules/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/auditSchedules/*}", + }, + ] + return http_options + class _BaseGetResourceEnrollmentStatus: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -242,6 +295,30 @@ def _get_http_options(): ] return http_options + class _BaseListAuditSchedules: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/auditSchedules", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*}/auditSchedules", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*}/auditSchedules", + }, + ] + return http_options + class _BaseListControls: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -286,6 +363,33 @@ def _get_http_options(): ] return http_options + class _BaseUpdateAuditSchedule: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{audit_schedule.name=projects/*/locations/*/auditSchedules/*}", + "body": "audit_schedule", + }, + { + "method": "patch", + "uri": "/v1/{audit_schedule.name=folders/*/locations/*/auditSchedules/*}", + "body": "audit_schedule", + }, + { + "method": "patch", + "uri": "/v1/{audit_schedule.name=organizations/*/locations/*/auditSchedules/*}", + "body": "audit_schedule", + }, + ] + return http_options + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py index 38c6f176ba39..4cefc35aa0b6 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py @@ -15,20 +15,25 @@ # from .auditmanager import ( AuditReport, + AuditSchedule, AuditScopeReport, ComplianceState, Control, ControlDetails, ControlFamily, + CreateAuditScheduleRequest, DestinationDetails, Enrollment, EnrollResourceRequest, GenerateAuditReportRequest, GenerateAuditScopeReportRequest, GetAuditReportRequest, + GetAuditScheduleRequest, GetResourceEnrollmentStatusRequest, ListAuditReportsRequest, ListAuditReportsResponse, + ListAuditSchedulesRequest, + ListAuditSchedulesResponse, ListControlsRequest, ListControlsResponse, ListResourceEnrollmentStatusesRequest, @@ -38,23 +43,31 @@ ReportGenerationProgress, ReportSummary, ResourceEnrollmentStatus, + ScheduleConfig, + ScheduleState, + UpdateAuditScheduleRequest, ) __all__ = ( "AuditReport", + "AuditSchedule", "AuditScopeReport", "Control", "ControlDetails", "ControlFamily", + "CreateAuditScheduleRequest", "DestinationDetails", "Enrollment", "EnrollResourceRequest", "GenerateAuditReportRequest", "GenerateAuditScopeReportRequest", "GetAuditReportRequest", + "GetAuditScheduleRequest", "GetResourceEnrollmentStatusRequest", "ListAuditReportsRequest", "ListAuditReportsResponse", + "ListAuditSchedulesRequest", + "ListAuditSchedulesResponse", "ListControlsRequest", "ListControlsResponse", "ListResourceEnrollmentStatusesRequest", @@ -63,6 +76,9 @@ "ReportGenerationProgress", "ReportSummary", "ResourceEnrollmentStatus", + "ScheduleConfig", + "UpdateAuditScheduleRequest", "ComplianceState", "OperationState", + "ScheduleState", ) diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py index dbb26fc7c110..295b443ec193 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore @@ -25,6 +26,7 @@ manifest={ "OperationState", "ComplianceState", + "ScheduleState", "EnrollResourceRequest", "GenerateAuditScopeReportRequest", "GenerateAuditReportRequest", @@ -47,6 +49,13 @@ "DestinationDetails", "ReportSummary", "ControlDetails", + "CreateAuditScheduleRequest", + "UpdateAuditScheduleRequest", + "GetAuditScheduleRequest", + "ListAuditSchedulesRequest", + "ListAuditSchedulesResponse", + "AuditSchedule", + "ScheduleConfig", }, ) @@ -115,6 +124,39 @@ class ComplianceState(proto.Enum): AUDIT_NOT_SUPPORTED = 5 +class ScheduleState(proto.Enum): + r"""State of an audit schedule. + + Values: + SCHEDULE_STATE_UNSPECIFIED (0): + Default value. This value is unused. + SCHEDULE_STATE_ACTIVE (1): + Schedule is active and will trigger runs. + SCHEDULE_STATE_PAUSED (2): + Schedule is paused and will not trigger runs. + SCHEDULE_STATE_COMPLETED (3): + Schedule end time has passed. + SCHEDULE_STATE_FAILED_SETUP (4): + Schedule setup failed during creation or + update. + SCHEDULE_STATE_ERROR (5): + Schedule is in an error state due to + persistent failure to trigger an audit. Manual + intervention is required. + SCHEDULE_STATE_DELETED (6): + Schedule has been marked for deletion by the + user. + """ + + SCHEDULE_STATE_UNSPECIFIED = 0 + SCHEDULE_STATE_ACTIVE = 1 + SCHEDULE_STATE_PAUSED = 2 + SCHEDULE_STATE_COMPLETED = 3 + SCHEDULE_STATE_FAILED_SETUP = 4 + SCHEDULE_STATE_ERROR = 5 + SCHEDULE_STATE_DELETED = 6 + + class EnrollResourceRequest(proto.Message): r"""Request message for [EnrollResource][google.cloud.auditmanager.v1.AuditManager.EnrollResource]. @@ -139,6 +181,23 @@ class EnrollResourceRequest(proto.Message): service agent at the organization or folder level, all the buckets that are associated with the service agent are available. + validate_only (bool): + Optional. If ``true``, only validates the request and does + not enroll the resource. This executes standard request + validation (such as schema, IAM, and destination checks) and + skips the apply phase. + + Use this field for the following purposes: + + - **Infrastructure as Code (IaC)**: Allow tools like + Terraform to run dry-run mutations (e.g., + ``terraform plan``) without creating real resources or + incurring costs. + - **User Interface Validation**: Enable real-time form and + permission validation in custom UIs before submitting + requests. + - **CI/CD & Automation**: Test your scripts, permissions, + and parameters safely without consuming resource quotas. """ class EligibleDestination(proto.Message): @@ -173,6 +232,10 @@ class EligibleDestination(proto.Message): number=2, message=EligibleDestination, ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) class GenerateAuditScopeReportRequest(proto.Message): @@ -197,6 +260,23 @@ class GenerateAuditScopeReportRequest(proto.Message): compliance_framework (str): Required. Framework (set of controls) that the audit scope report is generated against. For example, ``NIST_800_53``. + validate_only (bool): + Optional. If ``true``, only validates the request and does + not generate the audit scope report. This executes standard + request validation (such as schema, framework existence, + scope, and IAM checks) and skips the apply phase. + + Use this field for the following purposes: + + - **Infrastructure as Code (IaC)**: Allow tools like + Terraform to run dry-run mutations (e.g., + ``terraform plan``) without creating real resources or + incurring costs. + - **User Interface Validation**: Enable real-time form and + permission validation in custom UIs before submitting + requests. + - **CI/CD & Automation**: Test your scripts, permissions, + and parameters safely without consuming resource quotas. """ class AuditScopeReportFormat(proto.Enum): @@ -229,6 +309,10 @@ class AuditScopeReportFormat(proto.Enum): proto.STRING, number=5, ) + validate_only: bool = proto.Field( + proto.BOOL, + number=6, + ) class GenerateAuditReportRequest(proto.Message): @@ -1216,4 +1300,389 @@ class ControlDetails(proto.Message): ) +class CreateAuditScheduleRequest(proto.Message): + r"""Request message for + [CreateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.CreateAuditSchedule]. + + Attributes: + parent (str): + Required. Project or folder that this audit schedule is for, + in one of the following formats: + + - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + audit_schedule (google.cloud.auditmanager_v1.types.AuditSchedule): + Required. Audit schedule to create. + audit_schedule_id (str): + Required. ID to use for the audit schedule, + which becomes the final component of the audit + schedule's resource name. + validate_only (bool): + Optional. If ``true``, only validates the request and does + not create the audit schedule. This executes standard + request validation (such as schema, framework existence, + scope, and IAM checks) and skips the apply phase. + + Use this field for the following purposes: + + - **Infrastructure as Code (IaC)**: Allow tools like + Terraform to run dry-run mutations (e.g., + ``terraform plan``) without creating real resources or + incurring costs. + - **User Interface Validation**: Enable real-time form and + permission validation in custom UIs before submitting + requests. + - **CI/CD & Automation**: Test your scripts, permissions, + and parameters safely without consuming resource quotas. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + audit_schedule: "AuditSchedule" = proto.Field( + proto.MESSAGE, + number=2, + message="AuditSchedule", + ) + audit_schedule_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateAuditScheduleRequest(proto.Message): + r"""Request message for + [UpdateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.UpdateAuditSchedule]. + + Attributes: + audit_schedule (google.cloud.auditmanager_v1.types.AuditSchedule): + Required. Audit schedule to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields to update. + validate_only (bool): + Optional. If ``true``, only validates the request and does + not update the audit schedule. This executes standard + request validation (such as schema, framework existence, + scope, and IAM checks) and skips the apply phase. + + Use this field for the following purposes: + + - **Infrastructure as Code (IaC)**: Allow tools like + Terraform to run dry-run mutations (e.g., + ``terraform plan``) without creating real resources or + incurring costs. + - **User Interface Validation**: Enable real-time form and + permission validation in custom UIs before submitting + requests. + - **CI/CD & Automation**: Test your scripts, permissions, + and parameters safely without consuming resource quotas. + """ + + audit_schedule: "AuditSchedule" = proto.Field( + proto.MESSAGE, + number=1, + message="AuditSchedule", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetAuditScheduleRequest(proto.Message): + r"""Request message for + [GetAuditSchedule][google.cloud.auditmanager.v1.AuditManager.GetAuditSchedule]. + + Attributes: + name (str): + Required. Name of the audit schedule to retrieve, in one of + the following formats: + + - ``projects/{project}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``folders/{folder}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``organizations/{organization}/locations/{location}/auditSchedules/{audit_schedule}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAuditSchedulesRequest(proto.Message): + r"""Request message for + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. + + Attributes: + parent (str): + Required. Parent for the audit schedule, in one of the + following formats: + + - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``organizations/{organization}/locations/{location}`` + page_size (int): + Optional. Maximum number of items to return + in a single page. The service might return fewer + items than this value. If unspecified, the + service picks an appropriate default. The + maximum value is 100; values above 100 are + reduced to 100. + page_token (str): + Optional. A page token, received from a + previous call, to retrieve the next page of + results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAuditSchedulesResponse(proto.Message): + r"""Response message for + [ListAuditSchedules][google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules]. + + Attributes: + audit_schedules (MutableSequence[google.cloud.auditmanager_v1.types.AuditSchedule]): + List of audit schedules. + next_page_token (str): + A token that you can send as the ``page_token`` in a + subsequent request to retrieve the next page of results. If + this field is empty, there are no subsequent pages. + unreachable (MutableSequence[str]): + Locations that can't be reached. + """ + + @property + def raw_page(self): + return self + + audit_schedules: MutableSequence["AuditSchedule"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AuditSchedule", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class AuditSchedule(proto.Message): + r"""An audit schedule, in one of the following formats: + + - ``projects/{project}/locations/{location}/auditSchedules/{audit_schedule}`` + - ``folders/{folder}/locations/{location}/auditSchedules/{audit_schedule}`` + + Attributes: + name (str): + Identifier. Unique identifier for the audit schedule. + Format: + projects/{project}/locations/{location}/auditSchedules/{audit_schedule} + folders/{folder}/locations/{location}/auditSchedules/{audit_schedule} + organizations/{organization}/locations/{location}/auditSchedules/{audit_schedule} + display_name (str): + Optional. Display name for the audit + schedule. + gcs_uri (str): + Required. Cloud Storage bucket where Audit Manager can + upload the audit report and evidence. The format is + ``gs://{bucket_name}``. + compliance_framework (str): + Required. Framework (set of controls) that the audit scope + report is generated against. For example, ``NIST_800_53``. + report_format (google.cloud.auditmanager_v1.types.AuditSchedule.AuditReportFormat): + Required. Format for the audit report. + schedule_config (google.cloud.auditmanager_v1.types.ScheduleConfig): + Required. Configuration that defines when and + how often audit runs are automatically triggered + for this schedule. + state (google.cloud.auditmanager_v1.types.ScheduleState): + Optional. State of the audit schedule. While most states are + managed by the system, you can use + [UpdateAuditSchedule][google.cloud.auditmanager.v1.AuditManager.UpdateAuditSchedule] + to start, pause, or delete the schedule. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the schedule was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the schedule was + last updated. + next_run_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Calculated timestamp for the + next scheduled run. + last_trigger_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the audit run was + last triggered. + error_message (str): + Output only. Describes the error if the + schedule is in an error state. + """ + + class AuditReportFormat(proto.Enum): + r"""Format for the audit report. + + Values: + AUDIT_REPORT_FORMAT_UNSPECIFIED (0): + Default value. This value is unused. + AUDIT_REPORT_FORMAT_ODF (1): + Open Document Format (ODF). + """ + + AUDIT_REPORT_FORMAT_UNSPECIFIED = 0 + AUDIT_REPORT_FORMAT_ODF = 1 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=3, + ) + compliance_framework: str = proto.Field( + proto.STRING, + number=4, + ) + report_format: AuditReportFormat = proto.Field( + proto.ENUM, + number=5, + enum=AuditReportFormat, + ) + schedule_config: "ScheduleConfig" = proto.Field( + proto.MESSAGE, + number=6, + message="ScheduleConfig", + ) + state: "ScheduleState" = proto.Field( + proto.ENUM, + number=7, + enum="ScheduleState", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + next_run_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + last_trigger_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + error_message: str = proto.Field( + proto.STRING, + number=13, + ) + + +class ScheduleConfig(proto.Message): + r"""Timing and frequency parameters for recurring audit runs. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Date and time when the first audit + run is triggered. Subsequent runs are based on + this time and the chosen frequency. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Date that the schedule stops. + If not specified, the schedule runs + indefinitely. + frequency (google.cloud.auditmanager_v1.types.ScheduleConfig.Frequency): + Required. Frequency of audit runs. + time_zone (str): + Optional. Time zone for the audit schedule in IANA format + (for example, ``America/New_York``). The time zone is used + to interpret the ``start_time`` and the ``end_time``, and to + calculate subsequent run dates. If not specified, the time + zone default is UTC. + """ + + class Frequency(proto.Enum): + r"""Frequency of audit runs. + + Values: + FREQUENCY_UNSPECIFIED (0): + Default value. This value is unused. + DAILY (1): + The audit runs every day. + WEEKLY (2): + The audit runs weekly on the same day of the week as + ``start_time``. + MONTHLY (3): + The audit runs monthly on the same day of the month as + ``start_time``. + QUARTERLY (4): + The audit runs quarterly (every 3 months) on the same day of + the month as ``start_time``. + ANNUALLY (5): + The audit runs annually on the same month and day as + ``start_time``. + """ + + FREQUENCY_UNSPECIFIED = 0 + DAILY = 1 + WEEKLY = 2 + MONTHLY = 3 + QUARTERLY = 4 + ANNUALLY = 5 + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + frequency: Frequency = proto.Field( + proto.ENUM, + number=3, + enum=Frequency, + ) + time_zone: str = proto.Field( + proto.STRING, + number=4, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_create_audit_schedule_async.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_create_audit_schedule_async.py new file mode 100644 index 000000000000..28713d441a9e --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_create_audit_schedule_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAuditSchedule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_CreateAuditSchedule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +async def sample_create_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.CreateAuditScheduleRequest( + parent="parent_value", + audit_schedule=audit_schedule, + audit_schedule_id="audit_schedule_id_value", + ) + + # Make the request + response = await client.create_audit_schedule(request=request) + + # Handle the response + print(response) + + +# [END auditmanager_v1_generated_AuditManager_CreateAuditSchedule_async] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_create_audit_schedule_sync.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_create_audit_schedule_sync.py new file mode 100644 index 000000000000..db081ceca922 --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_create_audit_schedule_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAuditSchedule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_CreateAuditSchedule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +def sample_create_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.CreateAuditScheduleRequest( + parent="parent_value", + audit_schedule=audit_schedule, + audit_schedule_id="audit_schedule_id_value", + ) + + # Make the request + response = client.create_audit_schedule(request=request) + + # Handle the response + print(response) + + +# [END auditmanager_v1_generated_AuditManager_CreateAuditSchedule_sync] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_get_audit_schedule_async.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_get_audit_schedule_async.py new file mode 100644 index 000000000000..cca08a94ad99 --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_get_audit_schedule_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAuditSchedule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_GetAuditSchedule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +async def sample_get_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + request = auditmanager_v1.GetAuditScheduleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_audit_schedule(request=request) + + # Handle the response + print(response) + + +# [END auditmanager_v1_generated_AuditManager_GetAuditSchedule_async] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_get_audit_schedule_sync.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_get_audit_schedule_sync.py new file mode 100644 index 000000000000..5d8ed5486d09 --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_get_audit_schedule_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAuditSchedule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_GetAuditSchedule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +def sample_get_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + request = auditmanager_v1.GetAuditScheduleRequest( + name="name_value", + ) + + # Make the request + response = client.get_audit_schedule(request=request) + + # Handle the response + print(response) + + +# [END auditmanager_v1_generated_AuditManager_GetAuditSchedule_sync] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_list_audit_schedules_async.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_list_audit_schedules_async.py new file mode 100644 index 000000000000..ed4c81b54740 --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_list_audit_schedules_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAuditSchedules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_ListAuditSchedules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +async def sample_list_audit_schedules(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + request = auditmanager_v1.ListAuditSchedulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_audit_schedules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END auditmanager_v1_generated_AuditManager_ListAuditSchedules_async] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_list_audit_schedules_sync.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_list_audit_schedules_sync.py new file mode 100644 index 000000000000..8621932f5a02 --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_list_audit_schedules_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAuditSchedules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_ListAuditSchedules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +def sample_list_audit_schedules(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + request = auditmanager_v1.ListAuditSchedulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_audit_schedules(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END auditmanager_v1_generated_AuditManager_ListAuditSchedules_sync] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_update_audit_schedule_async.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_update_audit_schedule_async.py new file mode 100644 index 000000000000..d7b6e5288d55 --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_update_audit_schedule_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAuditSchedule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_UpdateAuditSchedule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +async def sample_update_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerAsyncClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.UpdateAuditScheduleRequest( + audit_schedule=audit_schedule, + ) + + # Make the request + response = await client.update_audit_schedule(request=request) + + # Handle the response + print(response) + + +# [END auditmanager_v1_generated_AuditManager_UpdateAuditSchedule_async] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_update_audit_schedule_sync.py b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_update_audit_schedule_sync.py new file mode 100644 index 000000000000..11c6d74ff36d --- /dev/null +++ b/packages/google-cloud-auditmanager/samples/generated_samples/auditmanager_v1_generated_audit_manager_update_audit_schedule_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAuditSchedule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-auditmanager + + +# [START auditmanager_v1_generated_AuditManager_UpdateAuditSchedule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import auditmanager_v1 + + +def sample_update_audit_schedule(): + # Create a client + client = auditmanager_v1.AuditManagerClient() + + # Initialize request argument(s) + audit_schedule = auditmanager_v1.AuditSchedule() + audit_schedule.gcs_uri = "gcs_uri_value" + audit_schedule.compliance_framework = "compliance_framework_value" + audit_schedule.report_format = "AUDIT_REPORT_FORMAT_ODF" + audit_schedule.schedule_config.frequency = "ANNUALLY" + + request = auditmanager_v1.UpdateAuditScheduleRequest( + audit_schedule=audit_schedule, + ) + + # Make the request + response = client.update_audit_schedule(request=request) + + # Handle the response + print(response) + + +# [END auditmanager_v1_generated_AuditManager_UpdateAuditSchedule_sync] diff --git a/packages/google-cloud-auditmanager/samples/generated_samples/snippet_metadata_google.cloud.auditmanager.v1.json b/packages/google-cloud-auditmanager/samples/generated_samples/snippet_metadata_google.cloud.auditmanager.v1.json index 1faae82c8c20..d2b5ce606074 100644 --- a/packages/google-cloud-auditmanager/samples/generated_samples/snippet_metadata_google.cloud.auditmanager.v1.json +++ b/packages/google-cloud-auditmanager/samples/generated_samples/snippet_metadata_google.cloud.auditmanager.v1.json @@ -8,9 +8,186 @@ ], "language": "PYTHON", "name": "google-cloud-auditmanager", - "version": "0.3.1" + "version": "0.3.2" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient", + "shortName": "AuditManagerAsyncClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.create_audit_schedule", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.CreateAuditSchedule", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "CreateAuditSchedule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.CreateAuditScheduleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "audit_schedule", + "type": "google.cloud.auditmanager_v1.types.AuditSchedule" + }, + { + "name": "audit_schedule_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.types.AuditSchedule", + "shortName": "create_audit_schedule" + }, + "description": "Sample for CreateAuditSchedule", + "file": "auditmanager_v1_generated_audit_manager_create_audit_schedule_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_CreateAuditSchedule_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_create_audit_schedule_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient", + "shortName": "AuditManagerClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.create_audit_schedule", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.CreateAuditSchedule", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "CreateAuditSchedule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.CreateAuditScheduleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "audit_schedule", + "type": "google.cloud.auditmanager_v1.types.AuditSchedule" + }, + { + "name": "audit_schedule_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.types.AuditSchedule", + "shortName": "create_audit_schedule" + }, + "description": "Sample for CreateAuditSchedule", + "file": "auditmanager_v1_generated_audit_manager_create_audit_schedule_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_CreateAuditSchedule_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_create_audit_schedule_sync.py" + }, { "canonical": true, "clientMethod": { @@ -711,19 +888,19 @@ "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient", "shortName": "AuditManagerAsyncClient" }, - "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.get_resource_enrollment_status", + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.get_audit_schedule", "method": { - "fullName": "google.cloud.auditmanager.v1.AuditManager.GetResourceEnrollmentStatus", + "fullName": "google.cloud.auditmanager.v1.AuditManager.GetAuditSchedule", "service": { "fullName": "google.cloud.auditmanager.v1.AuditManager", "shortName": "AuditManager" }, - "shortName": "GetResourceEnrollmentStatus" + "shortName": "GetAuditSchedule" }, "parameters": [ { "name": "request", - "type": "google.cloud.auditmanager_v1.types.GetResourceEnrollmentStatusRequest" + "type": "google.cloud.auditmanager_v1.types.GetAuditScheduleRequest" }, { "name": "name", @@ -742,14 +919,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.auditmanager_v1.types.ResourceEnrollmentStatus", - "shortName": "get_resource_enrollment_status" + "resultType": "google.cloud.auditmanager_v1.types.AuditSchedule", + "shortName": "get_audit_schedule" }, - "description": "Sample for GetResourceEnrollmentStatus", - "file": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_async.py", + "description": "Sample for GetAuditSchedule", + "file": "auditmanager_v1_generated_audit_manager_get_audit_schedule_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "auditmanager_v1_generated_AuditManager_GetResourceEnrollmentStatus_async", + "regionTag": "auditmanager_v1_generated_AuditManager_GetAuditSchedule_async", "segments": [ { "end": 51, @@ -782,7 +959,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_async.py" + "title": "auditmanager_v1_generated_audit_manager_get_audit_schedule_async.py" }, { "canonical": true, @@ -791,19 +968,19 @@ "fullName": "google.cloud.auditmanager_v1.AuditManagerClient", "shortName": "AuditManagerClient" }, - "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.get_resource_enrollment_status", + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.get_audit_schedule", "method": { - "fullName": "google.cloud.auditmanager.v1.AuditManager.GetResourceEnrollmentStatus", + "fullName": "google.cloud.auditmanager.v1.AuditManager.GetAuditSchedule", "service": { "fullName": "google.cloud.auditmanager.v1.AuditManager", "shortName": "AuditManager" }, - "shortName": "GetResourceEnrollmentStatus" + "shortName": "GetAuditSchedule" }, "parameters": [ { "name": "request", - "type": "google.cloud.auditmanager_v1.types.GetResourceEnrollmentStatusRequest" + "type": "google.cloud.auditmanager_v1.types.GetAuditScheduleRequest" }, { "name": "name", @@ -822,14 +999,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.auditmanager_v1.types.ResourceEnrollmentStatus", - "shortName": "get_resource_enrollment_status" + "resultType": "google.cloud.auditmanager_v1.types.AuditSchedule", + "shortName": "get_audit_schedule" }, - "description": "Sample for GetResourceEnrollmentStatus", - "file": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_sync.py", + "description": "Sample for GetAuditSchedule", + "file": "auditmanager_v1_generated_audit_manager_get_audit_schedule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "auditmanager_v1_generated_AuditManager_GetResourceEnrollmentStatus_sync", + "regionTag": "auditmanager_v1_generated_AuditManager_GetAuditSchedule_sync", "segments": [ { "end": 51, @@ -862,7 +1039,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_sync.py" + "title": "auditmanager_v1_generated_audit_manager_get_audit_schedule_sync.py" }, { "canonical": true, @@ -872,22 +1049,22 @@ "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient", "shortName": "AuditManagerAsyncClient" }, - "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.list_audit_reports", + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.get_resource_enrollment_status", "method": { - "fullName": "google.cloud.auditmanager.v1.AuditManager.ListAuditReports", + "fullName": "google.cloud.auditmanager.v1.AuditManager.GetResourceEnrollmentStatus", "service": { "fullName": "google.cloud.auditmanager.v1.AuditManager", "shortName": "AuditManager" }, - "shortName": "ListAuditReports" + "shortName": "GetResourceEnrollmentStatus" }, "parameters": [ { "name": "request", - "type": "google.cloud.auditmanager_v1.types.ListAuditReportsRequest" + "type": "google.cloud.auditmanager_v1.types.GetResourceEnrollmentStatusRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -903,22 +1080,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditReportsAsyncPager", - "shortName": "list_audit_reports" + "resultType": "google.cloud.auditmanager_v1.types.ResourceEnrollmentStatus", + "shortName": "get_resource_enrollment_status" }, - "description": "Sample for ListAuditReports", - "file": "auditmanager_v1_generated_audit_manager_list_audit_reports_async.py", + "description": "Sample for GetResourceEnrollmentStatus", + "file": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "auditmanager_v1_generated_AuditManager_ListAuditReports_async", + "regionTag": "auditmanager_v1_generated_AuditManager_GetResourceEnrollmentStatus_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -938,12 +1115,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "auditmanager_v1_generated_audit_manager_list_audit_reports_async.py" + "title": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_async.py" }, { "canonical": true, @@ -952,22 +1129,22 @@ "fullName": "google.cloud.auditmanager_v1.AuditManagerClient", "shortName": "AuditManagerClient" }, - "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.list_audit_reports", + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.get_resource_enrollment_status", "method": { - "fullName": "google.cloud.auditmanager.v1.AuditManager.ListAuditReports", + "fullName": "google.cloud.auditmanager.v1.AuditManager.GetResourceEnrollmentStatus", "service": { "fullName": "google.cloud.auditmanager.v1.AuditManager", "shortName": "AuditManager" }, - "shortName": "ListAuditReports" + "shortName": "GetResourceEnrollmentStatus" }, "parameters": [ { "name": "request", - "type": "google.cloud.auditmanager_v1.types.ListAuditReportsRequest" + "type": "google.cloud.auditmanager_v1.types.GetResourceEnrollmentStatusRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -983,22 +1160,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditReportsPager", - "shortName": "list_audit_reports" + "resultType": "google.cloud.auditmanager_v1.types.ResourceEnrollmentStatus", + "shortName": "get_resource_enrollment_status" }, - "description": "Sample for ListAuditReports", - "file": "auditmanager_v1_generated_audit_manager_list_audit_reports_sync.py", + "description": "Sample for GetResourceEnrollmentStatus", + "file": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "auditmanager_v1_generated_AuditManager_ListAuditReports_sync", + "regionTag": "auditmanager_v1_generated_AuditManager_GetResourceEnrollmentStatus_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1018,12 +1195,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "auditmanager_v1_generated_audit_manager_list_audit_reports_sync.py" + "title": "auditmanager_v1_generated_audit_manager_get_resource_enrollment_status_sync.py" }, { "canonical": true, @@ -1033,19 +1210,19 @@ "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient", "shortName": "AuditManagerAsyncClient" }, - "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.list_controls", + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.list_audit_reports", "method": { - "fullName": "google.cloud.auditmanager.v1.AuditManager.ListControls", + "fullName": "google.cloud.auditmanager.v1.AuditManager.ListAuditReports", "service": { "fullName": "google.cloud.auditmanager.v1.AuditManager", "shortName": "AuditManager" }, - "shortName": "ListControls" + "shortName": "ListAuditReports" }, "parameters": [ { "name": "request", - "type": "google.cloud.auditmanager_v1.types.ListControlsRequest" + "type": "google.cloud.auditmanager_v1.types.ListAuditReportsRequest" }, { "name": "parent", @@ -1064,14 +1241,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListControlsAsyncPager", - "shortName": "list_controls" + "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditReportsAsyncPager", + "shortName": "list_audit_reports" }, - "description": "Sample for ListControls", - "file": "auditmanager_v1_generated_audit_manager_list_controls_async.py", + "description": "Sample for ListAuditReports", + "file": "auditmanager_v1_generated_audit_manager_list_audit_reports_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "auditmanager_v1_generated_AuditManager_ListControls_async", + "regionTag": "auditmanager_v1_generated_AuditManager_ListAuditReports_async", "segments": [ { "end": 52, @@ -1104,7 +1281,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "auditmanager_v1_generated_audit_manager_list_controls_async.py" + "title": "auditmanager_v1_generated_audit_manager_list_audit_reports_async.py" }, { "canonical": true, @@ -1113,19 +1290,19 @@ "fullName": "google.cloud.auditmanager_v1.AuditManagerClient", "shortName": "AuditManagerClient" }, - "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.list_controls", + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.list_audit_reports", "method": { - "fullName": "google.cloud.auditmanager.v1.AuditManager.ListControls", + "fullName": "google.cloud.auditmanager.v1.AuditManager.ListAuditReports", "service": { "fullName": "google.cloud.auditmanager.v1.AuditManager", "shortName": "AuditManager" }, - "shortName": "ListControls" + "shortName": "ListAuditReports" }, "parameters": [ { "name": "request", - "type": "google.cloud.auditmanager_v1.types.ListControlsRequest" + "type": "google.cloud.auditmanager_v1.types.ListAuditReportsRequest" }, { "name": "parent", @@ -1144,12 +1321,334 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListControlsPager", - "shortName": "list_controls" + "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditReportsPager", + "shortName": "list_audit_reports" }, - "description": "Sample for ListControls", - "file": "auditmanager_v1_generated_audit_manager_list_controls_sync.py", - "language": "PYTHON", + "description": "Sample for ListAuditReports", + "file": "auditmanager_v1_generated_audit_manager_list_audit_reports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_ListAuditReports_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_list_audit_reports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient", + "shortName": "AuditManagerAsyncClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.list_audit_schedules", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "ListAuditSchedules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.ListAuditSchedulesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditSchedulesAsyncPager", + "shortName": "list_audit_schedules" + }, + "description": "Sample for ListAuditSchedules", + "file": "auditmanager_v1_generated_audit_manager_list_audit_schedules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_ListAuditSchedules_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_list_audit_schedules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient", + "shortName": "AuditManagerClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.list_audit_schedules", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.ListAuditSchedules", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "ListAuditSchedules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.ListAuditSchedulesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListAuditSchedulesPager", + "shortName": "list_audit_schedules" + }, + "description": "Sample for ListAuditSchedules", + "file": "auditmanager_v1_generated_audit_manager_list_audit_schedules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_ListAuditSchedules_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_list_audit_schedules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient", + "shortName": "AuditManagerAsyncClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.list_controls", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.ListControls", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.ListControlsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListControlsAsyncPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "auditmanager_v1_generated_audit_manager_list_controls_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_ListControls_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_list_controls_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient", + "shortName": "AuditManagerClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.list_controls", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.ListControls", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "ListControls" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.ListControlsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.services.audit_manager.pagers.ListControlsPager", + "shortName": "list_controls" + }, + "description": "Sample for ListControls", + "file": "auditmanager_v1_generated_audit_manager_list_controls_sync.py", + "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "auditmanager_v1_generated_AuditManager_ListControls_sync", "segments": [ @@ -1346,6 +1845,175 @@ } ], "title": "auditmanager_v1_generated_audit_manager_list_resource_enrollment_statuses_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient", + "shortName": "AuditManagerAsyncClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerAsyncClient.update_audit_schedule", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.UpdateAuditSchedule", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "UpdateAuditSchedule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.UpdateAuditScheduleRequest" + }, + { + "name": "audit_schedule", + "type": "google.cloud.auditmanager_v1.types.AuditSchedule" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.types.AuditSchedule", + "shortName": "update_audit_schedule" + }, + "description": "Sample for UpdateAuditSchedule", + "file": "auditmanager_v1_generated_audit_manager_update_audit_schedule_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_UpdateAuditSchedule_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_update_audit_schedule_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient", + "shortName": "AuditManagerClient" + }, + "fullName": "google.cloud.auditmanager_v1.AuditManagerClient.update_audit_schedule", + "method": { + "fullName": "google.cloud.auditmanager.v1.AuditManager.UpdateAuditSchedule", + "service": { + "fullName": "google.cloud.auditmanager.v1.AuditManager", + "shortName": "AuditManager" + }, + "shortName": "UpdateAuditSchedule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.auditmanager_v1.types.UpdateAuditScheduleRequest" + }, + { + "name": "audit_schedule", + "type": "google.cloud.auditmanager_v1.types.AuditSchedule" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.auditmanager_v1.types.AuditSchedule", + "shortName": "update_audit_schedule" + }, + "description": "Sample for UpdateAuditSchedule", + "file": "auditmanager_v1_generated_audit_manager_update_audit_schedule_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "auditmanager_v1_generated_AuditManager_UpdateAuditSchedule_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "auditmanager_v1_generated_audit_manager_update_audit_schedule_sync.py" } ] } diff --git a/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py b/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py index d50420f08ab4..4eac856e58a6 100644 --- a/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py +++ b/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py @@ -40,6 +40,7 @@ import google.api_core.operation_async as operation_async # type: ignore import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.api_core import ( client_options, @@ -1061,11 +1062,11 @@ def test_audit_manager_client_create_channel_credentials_file( @pytest.mark.parametrize( "request_type", [ - auditmanager.EnrollResourceRequest(), + auditmanager.CreateAuditScheduleRequest(), {}, ], ) -def test_enroll_resource(request_type, transport: str = "grpc"): +def test_create_audit_schedule(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1076,25 +1077,42 @@ def test_enroll_resource(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.Enrollment( + call.return_value = auditmanager.AuditSchedule( name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", ) - response = client.enroll_resource(request) + response = client.create_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = auditmanager.EnrollResourceRequest() + request = auditmanager.CreateAuditScheduleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.Enrollment) + assert isinstance(response, auditmanager.AuditSchedule) assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" -def test_enroll_resource_non_empty_request_with_auto_populated_field(): +def test_create_audit_schedule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( @@ -1105,25 +1123,29 @@ def test_enroll_resource_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = auditmanager.EnrollResourceRequest( - scope="scope_value", + request = auditmanager.CreateAuditScheduleRequest( + parent="parent_value", + audit_schedule_id="audit_schedule_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.enroll_resource(request=request) + client.create_audit_schedule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = auditmanager.EnrollResourceRequest( - scope="scope_value", + request_msg = auditmanager.CreateAuditScheduleRequest( + parent="parent_value", + audit_schedule_id="audit_schedule_id_value", ) assert args[0] == request_msg -def test_enroll_resource_use_cached_wrapped_rpc(): +def test_create_audit_schedule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -1137,21 +1159,26 @@ def test_enroll_resource_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.enroll_resource in client._transport._wrapped_methods + assert ( + client._transport.create_audit_schedule + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.enroll_resource] = mock_rpc + client._transport._wrapped_methods[client._transport.create_audit_schedule] = ( + mock_rpc + ) request = {} - client.enroll_resource(request) + client.create_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.enroll_resource(request) + client.create_audit_schedule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1159,7 +1186,7 @@ def test_enroll_resource_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_enroll_resource_async_use_cached_wrapped_rpc( +async def test_create_audit_schedule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1176,7 +1203,7 @@ async def test_enroll_resource_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.enroll_resource + client._client._transport.create_audit_schedule in client._client._transport._wrapped_methods ) @@ -1184,16 +1211,16 @@ async def test_enroll_resource_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.enroll_resource + client._client._transport.create_audit_schedule ] = mock_rpc request = {} - await client.enroll_resource(request) + await client.create_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.enroll_resource(request) + await client.create_audit_schedule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1204,11 +1231,13 @@ async def test_enroll_resource_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.EnrollResourceRequest(), + auditmanager.CreateAuditScheduleRequest(), {}, ], ) -async def test_enroll_resource_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_audit_schedule_async( + request_type, transport: str = "grpc_asyncio" +): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1219,41 +1248,60 @@ async def test_enroll_resource_async(request_type, transport: str = "grpc_asynci request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.Enrollment( + auditmanager.AuditSchedule( name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", ) ) - response = await client.enroll_resource(request) + response = await client.create_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.EnrollResourceRequest() + request = auditmanager.CreateAuditScheduleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.Enrollment) + assert isinstance(response, auditmanager.AuditSchedule) assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" -def test_enroll_resource_field_headers(): +def test_create_audit_schedule_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.EnrollResourceRequest() + request = auditmanager.CreateAuditScheduleRequest() - request.scope = "scope_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: - call.return_value = auditmanager.Enrollment() - client.enroll_resource(request) + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: + call.return_value = auditmanager.AuditSchedule() + client.create_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -1264,28 +1312,30 @@ def test_enroll_resource_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "scope=scope_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_enroll_resource_field_headers_async(): +async def test_create_audit_schedule_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.EnrollResourceRequest() + request = auditmanager.CreateAuditScheduleRequest() - request.scope = "scope_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.Enrollment() + auditmanager.AuditSchedule() ) - await client.enroll_resource(request) + await client.create_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -1296,47 +1346,45 @@ async def test_enroll_resource_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "scope=scope_value", + "parent=parent_value", ) in kw["metadata"] -def test_enroll_resource_flattened(): +def test_create_audit_schedule_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.Enrollment() + call.return_value = auditmanager.AuditSchedule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.enroll_resource( - scope="scope_value", - destinations=[ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ], + client.create_audit_schedule( + parent="parent_value", + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + audit_schedule_id="audit_schedule_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].scope - mock_val = "scope_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].destinations - mock_val = [ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ] + arg = args[0].audit_schedule + mock_val = auditmanager.AuditSchedule(name="name_value") + assert arg == mock_val + arg = args[0].audit_schedule_id + mock_val = "audit_schedule_id_value" assert arg == mock_val -def test_enroll_resource_flattened_error(): +def test_create_audit_schedule_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -1344,60 +1392,55 @@ def test_enroll_resource_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.enroll_resource( - auditmanager.EnrollResourceRequest(), - scope="scope_value", - destinations=[ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ], + client.create_audit_schedule( + auditmanager.CreateAuditScheduleRequest(), + parent="parent_value", + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + audit_schedule_id="audit_schedule_id_value", ) @pytest.mark.asyncio -async def test_enroll_resource_flattened_async(): +async def test_create_audit_schedule_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.Enrollment() + call.return_value = auditmanager.AuditSchedule() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.Enrollment() + auditmanager.AuditSchedule() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.enroll_resource( - scope="scope_value", - destinations=[ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ], + response = await client.create_audit_schedule( + parent="parent_value", + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + audit_schedule_id="audit_schedule_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].scope - mock_val = "scope_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].destinations - mock_val = [ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ] + arg = args[0].audit_schedule + mock_val = auditmanager.AuditSchedule(name="name_value") + assert arg == mock_val + arg = args[0].audit_schedule_id + mock_val = "audit_schedule_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_enroll_resource_flattened_error_async(): +async def test_create_audit_schedule_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -1405,25 +1448,22 @@ async def test_enroll_resource_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.enroll_resource( - auditmanager.EnrollResourceRequest(), - scope="scope_value", - destinations=[ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ], + await client.create_audit_schedule( + auditmanager.CreateAuditScheduleRequest(), + parent="parent_value", + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + audit_schedule_id="audit_schedule_id_value", ) @pytest.mark.parametrize( "request_type", [ - auditmanager.GenerateAuditScopeReportRequest(), + auditmanager.UpdateAuditScheduleRequest(), {}, ], ) -def test_generate_audit_scope_report(request_type, transport: str = "grpc"): +def test_update_audit_schedule(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1435,27 +1475,41 @@ def test_generate_audit_scope_report(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" + type(client.transport.update_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.AuditScopeReport( + call.return_value = auditmanager.AuditSchedule( name="name_value", - scope_report_contents=b"scope_report_contents_blob", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", ) - response = client.generate_audit_scope_report(request) + response = client.update_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = auditmanager.GenerateAuditScopeReportRequest() + request = auditmanager.UpdateAuditScheduleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.AuditScopeReport) + assert isinstance(response, auditmanager.AuditSchedule) assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" -def test_generate_audit_scope_report_non_empty_request_with_auto_populated_field(): +def test_update_audit_schedule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( @@ -1466,31 +1520,23 @@ def test_generate_audit_scope_report_non_empty_request_with_auto_populated_field # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = auditmanager.GenerateAuditScopeReportRequest( - scope="scope_value", - compliance_standard="compliance_standard_value", - compliance_framework="compliance_framework_value", - ) + request = auditmanager.UpdateAuditScheduleRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" + type(client.transport.update_audit_schedule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.generate_audit_scope_report(request=request) + client.update_audit_schedule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GenerateAuditScopeReportRequest( - scope="scope_value", - compliance_standard="compliance_standard_value", - compliance_framework="compliance_framework_value", - ) + request_msg = auditmanager.UpdateAuditScheduleRequest() assert args[0] == request_msg -def test_generate_audit_scope_report_use_cached_wrapped_rpc(): +def test_update_audit_schedule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -1505,7 +1551,7 @@ def test_generate_audit_scope_report_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.generate_audit_scope_report + client._transport.update_audit_schedule in client._transport._wrapped_methods ) @@ -1514,16 +1560,16 @@ def test_generate_audit_scope_report_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.generate_audit_scope_report - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_audit_schedule] = ( + mock_rpc + ) request = {} - client.generate_audit_scope_report(request) + client.update_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.generate_audit_scope_report(request) + client.update_audit_schedule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1531,7 +1577,7 @@ def test_generate_audit_scope_report_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_generate_audit_scope_report_async_use_cached_wrapped_rpc( +async def test_update_audit_schedule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1548,7 +1594,7 @@ async def test_generate_audit_scope_report_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.generate_audit_scope_report + client._client._transport.update_audit_schedule in client._client._transport._wrapped_methods ) @@ -1556,16 +1602,16 @@ async def test_generate_audit_scope_report_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.generate_audit_scope_report + client._client._transport.update_audit_schedule ] = mock_rpc request = {} - await client.generate_audit_scope_report(request) + await client.update_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.generate_audit_scope_report(request) + await client.update_audit_schedule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1576,11 +1622,11 @@ async def test_generate_audit_scope_report_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.GenerateAuditScopeReportRequest(), + auditmanager.UpdateAuditScheduleRequest(), {}, ], ) -async def test_generate_audit_scope_report_async( +async def test_update_audit_schedule_async( request_type, transport: str = "grpc_asyncio" ): client = AuditManagerAsyncClient( @@ -1594,44 +1640,59 @@ async def test_generate_audit_scope_report_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" + type(client.transport.update_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditScopeReport( + auditmanager.AuditSchedule( name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", ) ) - response = await client.generate_audit_scope_report(request) + response = await client.update_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.GenerateAuditScopeReportRequest() + request = auditmanager.UpdateAuditScheduleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.AuditScopeReport) + assert isinstance(response, auditmanager.AuditSchedule) assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" -def test_generate_audit_scope_report_field_headers(): +def test_update_audit_schedule_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GenerateAuditScopeReportRequest() + request = auditmanager.UpdateAuditScheduleRequest() - request.scope = "scope_value" + request.audit_schedule.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" + type(client.transport.update_audit_schedule), "__call__" ) as call: - call.return_value = auditmanager.AuditScopeReport() - client.generate_audit_scope_report(request) + call.return_value = auditmanager.AuditSchedule() + client.update_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -1642,30 +1703,30 @@ def test_generate_audit_scope_report_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "scope=scope_value", + "audit_schedule.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_generate_audit_scope_report_field_headers_async(): +async def test_update_audit_schedule_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GenerateAuditScopeReportRequest() + request = auditmanager.UpdateAuditScheduleRequest() - request.scope = "scope_value" + request.audit_schedule.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" + type(client.transport.update_audit_schedule), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditScopeReport() + auditmanager.AuditSchedule() ) - await client.generate_audit_scope_report(request) + await client.update_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -1676,45 +1737,41 @@ async def test_generate_audit_scope_report_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "scope=scope_value", + "audit_schedule.name=name_value", ) in kw["metadata"] -def test_generate_audit_scope_report_flattened(): +def test_update_audit_schedule_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" + type(client.transport.update_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.AuditScopeReport() + call.return_value = auditmanager.AuditSchedule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.generate_audit_scope_report( - scope="scope_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, + client.update_audit_schedule( + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].scope - mock_val = "scope_value" + arg = args[0].audit_schedule + mock_val = auditmanager.AuditSchedule(name="name_value") assert arg == mock_val - arg = args[0].compliance_standard - mock_val = "compliance_standard_value" - assert arg == mock_val - arg = args[0].report_format - mock_val = auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_generate_audit_scope_report_flattened_error(): +def test_update_audit_schedule_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -1722,55 +1779,50 @@ def test_generate_audit_scope_report_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.generate_audit_scope_report( - auditmanager.GenerateAuditScopeReportRequest(), - scope="scope_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, + client.update_audit_schedule( + auditmanager.UpdateAuditScheduleRequest(), + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_generate_audit_scope_report_flattened_async(): +async def test_update_audit_schedule_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" + type(client.transport.update_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.AuditScopeReport() + call.return_value = auditmanager.AuditSchedule() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditScopeReport() + auditmanager.AuditSchedule() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.generate_audit_scope_report( - scope="scope_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, + response = await client.update_audit_schedule( + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].scope - mock_val = "scope_value" - assert arg == mock_val - arg = args[0].compliance_standard - mock_val = "compliance_standard_value" + arg = args[0].audit_schedule + mock_val = auditmanager.AuditSchedule(name="name_value") assert arg == mock_val - arg = args[0].report_format - mock_val = auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_generate_audit_scope_report_flattened_error_async(): +async def test_update_audit_schedule_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -1778,22 +1830,21 @@ async def test_generate_audit_scope_report_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.generate_audit_scope_report( - auditmanager.GenerateAuditScopeReportRequest(), - scope="scope_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, + await client.update_audit_schedule( + auditmanager.UpdateAuditScheduleRequest(), + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - auditmanager.GenerateAuditReportRequest(), + auditmanager.GetAuditScheduleRequest(), {}, ], ) -def test_generate_audit_report(request_type, transport: str = "grpc"): +def test_get_audit_schedule(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1805,23 +1856,41 @@ def test_generate_audit_report(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" + type(client.transport.get_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.generate_audit_report(request) + call.return_value = auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) + response = client.get_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = auditmanager.GenerateAuditReportRequest() + request = auditmanager.GetAuditScheduleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, auditmanager.AuditSchedule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" -def test_generate_audit_report_non_empty_request_with_auto_populated_field(): +def test_get_audit_schedule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( @@ -1832,33 +1901,27 @@ def test_generate_audit_report_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = auditmanager.GenerateAuditReportRequest( - gcs_uri="gcs_uri_value", - scope="scope_value", - compliance_standard="compliance_standard_value", - compliance_framework="compliance_framework_value", + request = auditmanager.GetAuditScheduleRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" + type(client.transport.get_audit_schedule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.generate_audit_report(request=request) + client.get_audit_schedule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GenerateAuditReportRequest( - gcs_uri="gcs_uri_value", - scope="scope_value", - compliance_standard="compliance_standard_value", - compliance_framework="compliance_framework_value", + request_msg = auditmanager.GetAuditScheduleRequest( + name="name_value", ) assert args[0] == request_msg -def test_generate_audit_report_use_cached_wrapped_rpc(): +def test_get_audit_schedule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -1873,8 +1936,7 @@ def test_generate_audit_report_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.generate_audit_report - in client._transport._wrapped_methods + client._transport.get_audit_schedule in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -1882,21 +1944,16 @@ def test_generate_audit_report_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.generate_audit_report] = ( + client._transport._wrapped_methods[client._transport.get_audit_schedule] = ( mock_rpc ) request = {} - client.generate_audit_report(request) + client.get_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.generate_audit_report(request) + client.get_audit_schedule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1904,7 +1961,7 @@ def test_generate_audit_report_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_generate_audit_report_async_use_cached_wrapped_rpc( +async def test_get_audit_schedule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1921,7 +1978,7 @@ async def test_generate_audit_report_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.generate_audit_report + client._client._transport.get_audit_schedule in client._client._transport._wrapped_methods ) @@ -1929,21 +1986,16 @@ async def test_generate_audit_report_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.generate_audit_report + client._client._transport.get_audit_schedule ] = mock_rpc request = {} - await client.generate_audit_report(request) + await client.get_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.generate_audit_report(request) + await client.get_audit_schedule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1954,13 +2006,11 @@ async def test_generate_audit_report_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.GenerateAuditReportRequest(), + auditmanager.GetAuditScheduleRequest(), {}, ], ) -async def test_generate_audit_report_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_get_audit_schedule_async(request_type, transport: str = "grpc_asyncio"): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1972,41 +2022,59 @@ async def test_generate_audit_report_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" + type(client.transport.get_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) ) - response = await client.generate_audit_report(request) + response = await client.get_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.GenerateAuditReportRequest() + request = auditmanager.GetAuditScheduleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, auditmanager.AuditSchedule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" -def test_generate_audit_report_field_headers(): +def test_get_audit_schedule_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GenerateAuditReportRequest() + request = auditmanager.GetAuditScheduleRequest() - request.scope = "scope_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" + type(client.transport.get_audit_schedule), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.generate_audit_report(request) + call.return_value = auditmanager.AuditSchedule() + client.get_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2017,30 +2085,30 @@ def test_generate_audit_report_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "scope=scope_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_generate_audit_report_field_headers_async(): +async def test_get_audit_schedule_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GenerateAuditReportRequest() + request = auditmanager.GetAuditScheduleRequest() - request.scope = "scope_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" + type(client.transport.get_audit_schedule), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + auditmanager.AuditSchedule() ) - await client.generate_audit_report(request) + await client.get_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2051,47 +2119,37 @@ async def test_generate_audit_report_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "scope=scope_value", + "name=name_value", ) in kw["metadata"] -def test_generate_audit_report_flattened(): +def test_get_audit_schedule_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" + type(client.transport.get_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = auditmanager.AuditSchedule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.generate_audit_report( - scope="scope_value", - gcs_uri="gcs_uri_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + client.get_audit_schedule( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].scope - mock_val = "scope_value" - assert arg == mock_val - arg = args[0].compliance_standard - mock_val = "compliance_standard_value" - assert arg == mock_val - arg = args[0].report_format - mock_val = auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - assert args[0].gcs_uri == "gcs_uri_value" -def test_generate_audit_report_flattened_error(): +def test_get_audit_schedule_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2099,58 +2157,45 @@ def test_generate_audit_report_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.generate_audit_report( - auditmanager.GenerateAuditReportRequest(), - scope="scope_value", - gcs_uri="gcs_uri_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + client.get_audit_schedule( + auditmanager.GetAuditScheduleRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_generate_audit_report_flattened_async(): +async def test_get_audit_schedule_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" + type(client.transport.get_audit_schedule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = auditmanager.AuditSchedule() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + auditmanager.AuditSchedule() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.generate_audit_report( - scope="scope_value", - gcs_uri="gcs_uri_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + response = await client.get_audit_schedule( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].scope - mock_val = "scope_value" - assert arg == mock_val - arg = args[0].compliance_standard - mock_val = "compliance_standard_value" - assert arg == mock_val - arg = args[0].report_format - mock_val = auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - assert args[0].gcs_uri == "gcs_uri_value" @pytest.mark.asyncio -async def test_generate_audit_report_flattened_error_async(): +async def test_get_audit_schedule_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2158,23 +2203,20 @@ async def test_generate_audit_report_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.generate_audit_report( - auditmanager.GenerateAuditReportRequest(), - scope="scope_value", - gcs_uri="gcs_uri_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + await client.get_audit_schedule( + auditmanager.GetAuditScheduleRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - auditmanager.ListAuditReportsRequest(), + auditmanager.ListAuditSchedulesRequest(), {}, ], ) -def test_list_audit_reports(request_type, transport: str = "grpc"): +def test_list_audit_schedules(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2186,26 +2228,28 @@ def test_list_audit_reports(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListAuditReportsResponse( + call.return_value = auditmanager.ListAuditSchedulesResponse( next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.list_audit_reports(request) + response = client.list_audit_schedules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = auditmanager.ListAuditReportsRequest() + request = auditmanager.ListAuditSchedulesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuditReportsPager) + assert isinstance(response, pagers.ListAuditSchedulesPager) assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_list_audit_reports_non_empty_request_with_auto_populated_field(): +def test_list_audit_schedules_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( @@ -2216,29 +2260,29 @@ def test_list_audit_reports_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = auditmanager.ListAuditReportsRequest( + request = auditmanager.ListAuditSchedulesRequest( parent="parent_value", page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_audit_reports(request=request) + client.list_audit_schedules(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListAuditReportsRequest( + request_msg = auditmanager.ListAuditSchedulesRequest( parent="parent_value", page_token="page_token_value", ) assert args[0] == request_msg -def test_list_audit_reports_use_cached_wrapped_rpc(): +def test_list_audit_schedules_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -2253,7 +2297,7 @@ def test_list_audit_reports_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_audit_reports in client._transport._wrapped_methods + client._transport.list_audit_schedules in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -2261,16 +2305,16 @@ def test_list_audit_reports_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_audit_reports] = ( + client._transport._wrapped_methods[client._transport.list_audit_schedules] = ( mock_rpc ) request = {} - client.list_audit_reports(request) + client.list_audit_schedules(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_audit_reports(request) + client.list_audit_schedules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2278,7 +2322,7 @@ def test_list_audit_reports_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_audit_reports_async_use_cached_wrapped_rpc( +async def test_list_audit_schedules_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2295,7 +2339,7 @@ async def test_list_audit_reports_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_audit_reports + client._client._transport.list_audit_schedules in client._client._transport._wrapped_methods ) @@ -2303,16 +2347,16 @@ async def test_list_audit_reports_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_audit_reports + client._client._transport.list_audit_schedules ] = mock_rpc request = {} - await client.list_audit_reports(request) + await client.list_audit_schedules(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_audit_reports(request) + await client.list_audit_schedules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2323,11 +2367,13 @@ async def test_list_audit_reports_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.ListAuditReportsRequest(), + auditmanager.ListAuditSchedulesRequest(), {}, ], ) -async def test_list_audit_reports_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_audit_schedules_async( + request_type, transport: str = "grpc_asyncio" +): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2339,44 +2385,46 @@ async def test_list_audit_reports_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListAuditReportsResponse( + auditmanager.ListAuditSchedulesResponse( next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.list_audit_reports(request) + response = await client.list_audit_schedules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.ListAuditReportsRequest() + request = auditmanager.ListAuditSchedulesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuditReportsAsyncPager) + assert isinstance(response, pagers.ListAuditSchedulesAsyncPager) assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_list_audit_reports_field_headers(): +def test_list_audit_schedules_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.ListAuditReportsRequest() + request = auditmanager.ListAuditSchedulesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: - call.return_value = auditmanager.ListAuditReportsResponse() - client.list_audit_reports(request) + call.return_value = auditmanager.ListAuditSchedulesResponse() + client.list_audit_schedules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2392,25 +2440,25 @@ def test_list_audit_reports_field_headers(): @pytest.mark.asyncio -async def test_list_audit_reports_field_headers_async(): +async def test_list_audit_schedules_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.ListAuditReportsRequest() + request = auditmanager.ListAuditSchedulesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListAuditReportsResponse() + auditmanager.ListAuditSchedulesResponse() ) - await client.list_audit_reports(request) + await client.list_audit_schedules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2425,20 +2473,20 @@ async def test_list_audit_reports_field_headers_async(): ) in kw["metadata"] -def test_list_audit_reports_flattened(): +def test_list_audit_schedules_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListAuditReportsResponse() + call.return_value = auditmanager.ListAuditSchedulesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_audit_reports( + client.list_audit_schedules( parent="parent_value", ) @@ -2451,7 +2499,7 @@ def test_list_audit_reports_flattened(): assert arg == mock_val -def test_list_audit_reports_flattened_error(): +def test_list_audit_schedules_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2459,31 +2507,31 @@ def test_list_audit_reports_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_audit_reports( - auditmanager.ListAuditReportsRequest(), + client.list_audit_schedules( + auditmanager.ListAuditSchedulesRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_audit_reports_flattened_async(): +async def test_list_audit_schedules_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListAuditReportsResponse() + call.return_value = auditmanager.ListAuditSchedulesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListAuditReportsResponse() + auditmanager.ListAuditSchedulesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_audit_reports( + response = await client.list_audit_schedules( parent="parent_value", ) @@ -2497,7 +2545,7 @@ async def test_list_audit_reports_flattened_async(): @pytest.mark.asyncio -async def test_list_audit_reports_flattened_error_async(): +async def test_list_audit_schedules_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2505,13 +2553,13 @@ async def test_list_audit_reports_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_audit_reports( - auditmanager.ListAuditReportsRequest(), + await client.list_audit_schedules( + auditmanager.ListAuditSchedulesRequest(), parent="parent_value", ) -def test_list_audit_reports_pager(transport_name: str = "grpc"): +def test_list_audit_schedules_pager(transport_name: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -2519,32 +2567,32 @@ def test_list_audit_reports_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], next_page_token="abc", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[], + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[], next_page_token="def", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), ], next_page_token="ghi", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], ), RuntimeError, @@ -2556,7 +2604,7 @@ def test_list_audit_reports_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_audit_reports(request={}, retry=retry, timeout=timeout) + pager = client.list_audit_schedules(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -2567,10 +2615,10 @@ def test_list_audit_reports_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, auditmanager.AuditReport) for i in results) + assert all(isinstance(i, auditmanager.AuditSchedule) for i in results) -def test_list_audit_reports_pages(transport_name: str = "grpc"): +def test_list_audit_schedules_pages(transport_name: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -2578,82 +2626,82 @@ def test_list_audit_reports_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" + type(client.transport.list_audit_schedules), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], next_page_token="abc", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[], + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[], next_page_token="def", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), ], next_page_token="ghi", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], ), RuntimeError, ) - pages = list(client.list_audit_reports(request={}).pages) + pages = list(client.list_audit_schedules(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_audit_reports_async_pager(): +async def test_list_audit_schedules_async_pager(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), + type(client.transport.list_audit_schedules), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], next_page_token="abc", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[], + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[], next_page_token="def", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), ], next_page_token="ghi", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], ), RuntimeError, ) - async_pager = await client.list_audit_reports( + async_pager = await client.list_audit_schedules( request={}, ) assert async_pager.next_page_token == "abc" @@ -2664,51 +2712,51 @@ async def test_list_audit_reports_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, auditmanager.AuditReport) for i in responses) + assert all(isinstance(i, auditmanager.AuditSchedule) for i in responses) @pytest.mark.asyncio -async def test_list_audit_reports_async_pages(): +async def test_list_audit_schedules_async_pages(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audit_reports), + type(client.transport.list_audit_schedules), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], next_page_token="abc", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[], + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[], next_page_token="def", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), ], next_page_token="ghi", ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), ], ), RuntimeError, ) pages = [] - async for page_ in (await client.list_audit_reports(request={})).pages: + async for page_ in (await client.list_audit_schedules(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -2717,11 +2765,11 @@ async def test_list_audit_reports_async_pages(): @pytest.mark.parametrize( "request_type", [ - auditmanager.GetAuditReportRequest(), + auditmanager.EnrollResourceRequest(), {}, ], ) -def test_get_audit_report(request_type, transport: str = "grpc"): +def test_enroll_resource(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2732,40 +2780,25 @@ def test_get_audit_report(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.AuditReport( + call.return_value = auditmanager.Enrollment( name="name_value", - operation_id="operation_id_value", - compliance_standard="compliance_standard_value", - scope="scope_value", - report_generation_state=auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS, - compliance_framework="compliance_framework_value", - scope_id="scope_id_value", ) - response = client.get_audit_report(request) + response = client.enroll_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = auditmanager.GetAuditReportRequest() + request = auditmanager.EnrollResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.AuditReport) + assert isinstance(response, auditmanager.Enrollment) assert response.name == "name_value" - assert response.operation_id == "operation_id_value" - assert response.compliance_standard == "compliance_standard_value" - assert response.scope == "scope_value" - assert ( - response.report_generation_state - == auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS - ) - assert response.compliance_framework == "compliance_framework_value" - assert response.scope_id == "scope_id_value" -def test_get_audit_report_non_empty_request_with_auto_populated_field(): +def test_enroll_resource_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( @@ -2776,25 +2809,25 @@ def test_get_audit_report_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = auditmanager.GetAuditReportRequest( - name="name_value", + request = auditmanager.EnrollResourceRequest( + scope="scope_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_audit_report(request=request) + client.enroll_resource(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GetAuditReportRequest( - name="name_value", + request_msg = auditmanager.EnrollResourceRequest( + scope="scope_value", ) assert args[0] == request_msg -def test_get_audit_report_use_cached_wrapped_rpc(): +def test_enroll_resource_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -2808,23 +2841,21 @@ def test_get_audit_report_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_audit_report in client._transport._wrapped_methods + assert client._transport.enroll_resource in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_audit_report] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.enroll_resource] = mock_rpc request = {} - client.get_audit_report(request) + client.enroll_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_audit_report(request) + client.enroll_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2832,7 +2863,7 @@ def test_get_audit_report_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_audit_report_async_use_cached_wrapped_rpc( +async def test_enroll_resource_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2849,7 +2880,7 @@ async def test_get_audit_report_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_audit_report + client._client._transport.enroll_resource in client._client._transport._wrapped_methods ) @@ -2857,16 +2888,16 @@ async def test_get_audit_report_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_audit_report + client._client._transport.enroll_resource ] = mock_rpc request = {} - await client.get_audit_report(request) + await client.enroll_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_audit_report(request) + await client.enroll_resource(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2877,11 +2908,11 @@ async def test_get_audit_report_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.GetAuditReportRequest(), + auditmanager.EnrollResourceRequest(), {}, ], ) -async def test_get_audit_report_async(request_type, transport: str = "grpc_asyncio"): +async def test_enroll_resource_async(request_type, transport: str = "grpc_asyncio"): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2892,56 +2923,41 @@ async def test_get_audit_report_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditReport( + auditmanager.Enrollment( name="name_value", - operation_id="operation_id_value", - compliance_standard="compliance_standard_value", - scope="scope_value", - report_generation_state=auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS, - compliance_framework="compliance_framework_value", - scope_id="scope_id_value", ) ) - response = await client.get_audit_report(request) + response = await client.enroll_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.GetAuditReportRequest() + request = auditmanager.EnrollResourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.AuditReport) + assert isinstance(response, auditmanager.Enrollment) assert response.name == "name_value" - assert response.operation_id == "operation_id_value" - assert response.compliance_standard == "compliance_standard_value" - assert response.scope == "scope_value" - assert ( - response.report_generation_state - == auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS - ) - assert response.compliance_framework == "compliance_framework_value" - assert response.scope_id == "scope_id_value" -def test_get_audit_report_field_headers(): +def test_enroll_resource_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GetAuditReportRequest() + request = auditmanager.EnrollResourceRequest() - request.name = "name_value" + request.scope = "scope_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: - call.return_value = auditmanager.AuditReport() - client.get_audit_report(request) + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + call.return_value = auditmanager.Enrollment() + client.enroll_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2952,28 +2968,28 @@ def test_get_audit_report_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "scope=scope_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_audit_report_field_headers_async(): +async def test_enroll_resource_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GetAuditReportRequest() + request = auditmanager.EnrollResourceRequest() - request.name = "name_value" + request.scope = "scope_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditReport() + auditmanager.Enrollment() ) - await client.get_audit_report(request) + await client.enroll_resource(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2984,35 +3000,47 @@ async def test_get_audit_report_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "scope=scope_value", ) in kw["metadata"] -def test_get_audit_report_flattened(): +def test_enroll_resource_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.AuditReport() + call.return_value = auditmanager.Enrollment() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_audit_report( - name="name_value", + client.enroll_resource( + scope="scope_value", + destinations=[ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].scope + mock_val = "scope_value" + assert arg == mock_val + arg = args[0].destinations + mock_val = [ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ] assert arg == mock_val -def test_get_audit_report_flattened_error(): +def test_enroll_resource_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3020,43 +3048,60 @@ def test_get_audit_report_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_audit_report( - auditmanager.GetAuditReportRequest(), - name="name_value", + client.enroll_resource( + auditmanager.EnrollResourceRequest(), + scope="scope_value", + destinations=[ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ], ) @pytest.mark.asyncio -async def test_get_audit_report_flattened_async(): +async def test_enroll_resource_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.AuditReport() + call.return_value = auditmanager.Enrollment() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditReport() + auditmanager.Enrollment() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_audit_report( - name="name_value", + response = await client.enroll_resource( + scope="scope_value", + destinations=[ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].scope + mock_val = "scope_value" + assert arg == mock_val + arg = args[0].destinations + mock_val = [ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ] assert arg == mock_val @pytest.mark.asyncio -async def test_get_audit_report_flattened_error_async(): +async def test_enroll_resource_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3064,20 +3109,25 @@ async def test_get_audit_report_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_audit_report( - auditmanager.GetAuditReportRequest(), - name="name_value", + await client.enroll_resource( + auditmanager.EnrollResourceRequest(), + scope="scope_value", + destinations=[ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ], ) @pytest.mark.parametrize( "request_type", [ - auditmanager.GetResourceEnrollmentStatusRequest(), + auditmanager.GenerateAuditScopeReportRequest(), {}, ], ) -def test_get_resource_enrollment_status(request_type, transport: str = "grpc"): +def test_generate_audit_scope_report(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3089,35 +3139,27 @@ def test_get_resource_enrollment_status(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" + type(client.transport.generate_audit_scope_report), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ResourceEnrollmentStatus( + call.return_value = auditmanager.AuditScopeReport( name="name_value", - enrolled=True, - display_name="display_name_value", - enrollment_state=auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED, + scope_report_contents=b"scope_report_contents_blob", ) - response = client.get_resource_enrollment_status(request) + response = client.generate_audit_scope_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = auditmanager.GetResourceEnrollmentStatusRequest() + request = auditmanager.GenerateAuditScopeReportRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.ResourceEnrollmentStatus) + assert isinstance(response, auditmanager.AuditScopeReport) assert response.name == "name_value" - assert response.enrolled is True - assert response.display_name == "display_name_value" - assert ( - response.enrollment_state - == auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED - ) -def test_get_resource_enrollment_status_non_empty_request_with_auto_populated_field(): +def test_generate_audit_scope_report_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( @@ -3128,27 +3170,31 @@ def test_get_resource_enrollment_status_non_empty_request_with_auto_populated_fi # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = auditmanager.GetResourceEnrollmentStatusRequest( - name="name_value", + request = auditmanager.GenerateAuditScopeReportRequest( + scope="scope_value", + compliance_standard="compliance_standard_value", + compliance_framework="compliance_framework_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" + type(client.transport.generate_audit_scope_report), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_resource_enrollment_status(request=request) + client.generate_audit_scope_report(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GetResourceEnrollmentStatusRequest( - name="name_value", + request_msg = auditmanager.GenerateAuditScopeReportRequest( + scope="scope_value", + compliance_standard="compliance_standard_value", + compliance_framework="compliance_framework_value", ) assert args[0] == request_msg -def test_get_resource_enrollment_status_use_cached_wrapped_rpc(): +def test_generate_audit_scope_report_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3163,7 +3209,7 @@ def test_get_resource_enrollment_status_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_resource_enrollment_status + client._transport.generate_audit_scope_report in client._transport._wrapped_methods ) @@ -3173,15 +3219,15 @@ def test_get_resource_enrollment_status_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_resource_enrollment_status + client._transport.generate_audit_scope_report ] = mock_rpc request = {} - client.get_resource_enrollment_status(request) + client.generate_audit_scope_report(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_resource_enrollment_status(request) + client.generate_audit_scope_report(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3189,7 +3235,7 @@ def test_get_resource_enrollment_status_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_resource_enrollment_status_async_use_cached_wrapped_rpc( +async def test_generate_audit_scope_report_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3206,7 +3252,7 @@ async def test_get_resource_enrollment_status_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_resource_enrollment_status + client._client._transport.generate_audit_scope_report in client._client._transport._wrapped_methods ) @@ -3214,16 +3260,16 @@ async def test_get_resource_enrollment_status_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_resource_enrollment_status + client._client._transport.generate_audit_scope_report ] = mock_rpc request = {} - await client.get_resource_enrollment_status(request) + await client.generate_audit_scope_report(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_resource_enrollment_status(request) + await client.generate_audit_scope_report(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3234,11 +3280,11 @@ async def test_get_resource_enrollment_status_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.GetResourceEnrollmentStatusRequest(), + auditmanager.GenerateAuditScopeReportRequest(), {}, ], ) -async def test_get_resource_enrollment_status_async( +async def test_generate_audit_scope_report_async( request_type, transport: str = "grpc_asyncio" ): client = AuditManagerAsyncClient( @@ -3252,53 +3298,44 @@ async def test_get_resource_enrollment_status_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" + type(client.transport.generate_audit_scope_report), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ResourceEnrollmentStatus( + auditmanager.AuditScopeReport( name="name_value", - enrolled=True, - display_name="display_name_value", - enrollment_state=auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED, ) ) - response = await client.get_resource_enrollment_status(request) + response = await client.generate_audit_scope_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.GetResourceEnrollmentStatusRequest() + request = auditmanager.GenerateAuditScopeReportRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, auditmanager.ResourceEnrollmentStatus) + assert isinstance(response, auditmanager.AuditScopeReport) assert response.name == "name_value" - assert response.enrolled is True - assert response.display_name == "display_name_value" - assert ( - response.enrollment_state - == auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED - ) -def test_get_resource_enrollment_status_field_headers(): +def test_generate_audit_scope_report_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GetResourceEnrollmentStatusRequest() + request = auditmanager.GenerateAuditScopeReportRequest() - request.name = "name_value" + request.scope = "scope_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" + type(client.transport.generate_audit_scope_report), "__call__" ) as call: - call.return_value = auditmanager.ResourceEnrollmentStatus() - client.get_resource_enrollment_status(request) + call.return_value = auditmanager.AuditScopeReport() + client.generate_audit_scope_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3309,30 +3346,30 @@ def test_get_resource_enrollment_status_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "scope=scope_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_resource_enrollment_status_field_headers_async(): +async def test_generate_audit_scope_report_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.GetResourceEnrollmentStatusRequest() + request = auditmanager.GenerateAuditScopeReportRequest() - request.name = "name_value" + request.scope = "scope_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" + type(client.transport.generate_audit_scope_report), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ResourceEnrollmentStatus() + auditmanager.AuditScopeReport() ) - await client.get_resource_enrollment_status(request) + await client.generate_audit_scope_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3343,37 +3380,45 @@ async def test_get_resource_enrollment_status_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "scope=scope_value", ) in kw["metadata"] -def test_get_resource_enrollment_status_flattened(): +def test_generate_audit_scope_report_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" + type(client.transport.generate_audit_scope_report), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ResourceEnrollmentStatus() + call.return_value = auditmanager.AuditScopeReport() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_resource_enrollment_status( - name="name_value", + client.generate_audit_scope_report( + scope="scope_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].scope + mock_val = "scope_value" + assert arg == mock_val + arg = args[0].compliance_standard + mock_val = "compliance_standard_value" + assert arg == mock_val + arg = args[0].report_format + mock_val = auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF assert arg == mock_val -def test_get_resource_enrollment_status_flattened_error(): +def test_generate_audit_scope_report_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3381,45 +3426,55 @@ def test_get_resource_enrollment_status_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_resource_enrollment_status( - auditmanager.GetResourceEnrollmentStatusRequest(), - name="name_value", + client.generate_audit_scope_report( + auditmanager.GenerateAuditScopeReportRequest(), + scope="scope_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, ) @pytest.mark.asyncio -async def test_get_resource_enrollment_status_flattened_async(): +async def test_generate_audit_scope_report_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" + type(client.transport.generate_audit_scope_report), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ResourceEnrollmentStatus() + call.return_value = auditmanager.AuditScopeReport() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ResourceEnrollmentStatus() + auditmanager.AuditScopeReport() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_resource_enrollment_status( - name="name_value", + response = await client.generate_audit_scope_report( + scope="scope_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].scope + mock_val = "scope_value" + assert arg == mock_val + arg = args[0].compliance_standard + mock_val = "compliance_standard_value" + assert arg == mock_val + arg = args[0].report_format + mock_val = auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF assert arg == mock_val @pytest.mark.asyncio -async def test_get_resource_enrollment_status_flattened_error_async(): +async def test_generate_audit_scope_report_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3427,20 +3482,22 @@ async def test_get_resource_enrollment_status_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_resource_enrollment_status( - auditmanager.GetResourceEnrollmentStatusRequest(), - name="name_value", + await client.generate_audit_scope_report( + auditmanager.GenerateAuditScopeReportRequest(), + scope="scope_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, ) @pytest.mark.parametrize( "request_type", [ - auditmanager.ListResourceEnrollmentStatusesRequest(), + auditmanager.GenerateAuditReportRequest(), {}, ], ) -def test_list_resource_enrollment_statuses(request_type, transport: str = "grpc"): +def test_generate_audit_report(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3452,26 +3509,23 @@ def test_list_resource_enrollment_statuses(request_type, transport: str = "grpc" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.generate_audit_report), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse( - next_page_token="next_page_token_value", - ) - response = client.list_resource_enrollment_statuses(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.generate_audit_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = auditmanager.ListResourceEnrollmentStatusesRequest() + request = auditmanager.GenerateAuditReportRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceEnrollmentStatusesPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_resource_enrollment_statuses_non_empty_request_with_auto_populated_field(): +def test_generate_audit_report_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( @@ -3482,29 +3536,33 @@ def test_list_resource_enrollment_statuses_non_empty_request_with_auto_populated # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = auditmanager.ListResourceEnrollmentStatusesRequest( - parent="parent_value", - page_token="page_token_value", + request = auditmanager.GenerateAuditReportRequest( + gcs_uri="gcs_uri_value", + scope="scope_value", + compliance_standard="compliance_standard_value", + compliance_framework="compliance_framework_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.generate_audit_report), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_resource_enrollment_statuses(request=request) + client.generate_audit_report(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListResourceEnrollmentStatusesRequest( - parent="parent_value", - page_token="page_token_value", + request_msg = auditmanager.GenerateAuditReportRequest( + gcs_uri="gcs_uri_value", + scope="scope_value", + compliance_standard="compliance_standard_value", + compliance_framework="compliance_framework_value", ) assert args[0] == request_msg -def test_list_resource_enrollment_statuses_use_cached_wrapped_rpc(): +def test_generate_audit_report_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3519,7 +3577,7 @@ def test_list_resource_enrollment_statuses_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_resource_enrollment_statuses + client._transport.generate_audit_report in client._transport._wrapped_methods ) @@ -3528,16 +3586,21 @@ def test_list_resource_enrollment_statuses_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_resource_enrollment_statuses - ] = mock_rpc + client._transport._wrapped_methods[client._transport.generate_audit_report] = ( + mock_rpc + ) request = {} - client.list_resource_enrollment_statuses(request) + client.generate_audit_report(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_resource_enrollment_statuses(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.generate_audit_report(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3545,7 +3608,7 @@ def test_list_resource_enrollment_statuses_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_resource_enrollment_statuses_async_use_cached_wrapped_rpc( +async def test_generate_audit_report_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3562,7 +3625,7 @@ async def test_list_resource_enrollment_statuses_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_resource_enrollment_statuses + client._client._transport.generate_audit_report in client._client._transport._wrapped_methods ) @@ -3570,16 +3633,21 @@ async def test_list_resource_enrollment_statuses_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_resource_enrollment_statuses + client._client._transport.generate_audit_report ] = mock_rpc request = {} - await client.list_resource_enrollment_statuses(request) + await client.generate_audit_report(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_resource_enrollment_statuses(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.generate_audit_report(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3590,11 +3658,11 @@ async def test_list_resource_enrollment_statuses_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.ListResourceEnrollmentStatusesRequest(), + auditmanager.GenerateAuditReportRequest(), {}, ], ) -async def test_list_resource_enrollment_statuses_async( +async def test_generate_audit_report_async( request_type, transport: str = "grpc_asyncio" ): client = AuditManagerAsyncClient( @@ -3608,44 +3676,41 @@ async def test_list_resource_enrollment_statuses_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.generate_audit_report), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListResourceEnrollmentStatusesResponse( - next_page_token="next_page_token_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_resource_enrollment_statuses(request) + response = await client.generate_audit_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.ListResourceEnrollmentStatusesRequest() + request = auditmanager.GenerateAuditReportRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceEnrollmentStatusesAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_resource_enrollment_statuses_field_headers(): +def test_generate_audit_report_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.ListResourceEnrollmentStatusesRequest() + request = auditmanager.GenerateAuditReportRequest() - request.parent = "parent_value" + request.scope = "scope_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.generate_audit_report), "__call__" ) as call: - call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() - client.list_resource_enrollment_statuses(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.generate_audit_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3656,30 +3721,30 @@ def test_list_resource_enrollment_statuses_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "scope=scope_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_resource_enrollment_statuses_field_headers_async(): +async def test_generate_audit_report_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.ListResourceEnrollmentStatusesRequest() + request = auditmanager.GenerateAuditReportRequest() - request.parent = "parent_value" + request.scope = "scope_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.generate_audit_report), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListResourceEnrollmentStatusesResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_resource_enrollment_statuses(request) + await client.generate_audit_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3690,37 +3755,47 @@ async def test_list_resource_enrollment_statuses_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "scope=scope_value", ) in kw["metadata"] -def test_list_resource_enrollment_statuses_flattened(): +def test_generate_audit_report_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.generate_audit_report), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_resource_enrollment_statuses( - parent="parent_value", + client.generate_audit_report( + scope="scope_value", + gcs_uri="gcs_uri_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].scope + mock_val = "scope_value" assert arg == mock_val + arg = args[0].compliance_standard + mock_val = "compliance_standard_value" + assert arg == mock_val + arg = args[0].report_format + mock_val = auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + assert arg == mock_val + assert args[0].gcs_uri == "gcs_uri_value" -def test_list_resource_enrollment_statuses_flattened_error(): +def test_generate_audit_report_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3728,45 +3803,58 @@ def test_list_resource_enrollment_statuses_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_resource_enrollment_statuses( - auditmanager.ListResourceEnrollmentStatusesRequest(), - parent="parent_value", + client.generate_audit_report( + auditmanager.GenerateAuditReportRequest(), + scope="scope_value", + gcs_uri="gcs_uri_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, ) @pytest.mark.asyncio -async def test_list_resource_enrollment_statuses_flattened_async(): +async def test_generate_audit_report_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.generate_audit_report), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListResourceEnrollmentStatusesResponse() + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_resource_enrollment_statuses( - parent="parent_value", + response = await client.generate_audit_report( + scope="scope_value", + gcs_uri="gcs_uri_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].scope + mock_val = "scope_value" + assert arg == mock_val + arg = args[0].compliance_standard + mock_val = "compliance_standard_value" assert arg == mock_val + arg = args[0].report_format + mock_val = auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + assert arg == mock_val + assert args[0].gcs_uri == "gcs_uri_value" @pytest.mark.asyncio -async def test_list_resource_enrollment_statuses_flattened_error_async(): +async def test_generate_audit_report_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3774,291 +3862,87 @@ async def test_list_resource_enrollment_statuses_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_resource_enrollment_statuses( - auditmanager.ListResourceEnrollmentStatusesRequest(), - parent="parent_value", + await client.generate_audit_report( + auditmanager.GenerateAuditReportRequest(), + scope="scope_value", + gcs_uri="gcs_uri_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, ) -def test_list_resource_enrollment_statuses_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.ListAuditReportsRequest(), + {}, + ], +) +def test_list_audit_reports(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" + type(client.transport.list_audit_reports), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="abc", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[], - next_page_token="def", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="ghi", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_resource_enrollment_statuses( - request={}, retry=retry, timeout=timeout + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ListAuditReportsResponse( + next_page_token="next_page_token_value", ) + response = client.list_audit_reports(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = auditmanager.ListAuditReportsRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, auditmanager.ResourceEnrollmentStatus) for i in results - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuditReportsPager) + assert response.next_page_token == "next_page_token_value" -def test_list_resource_enrollment_statuses_pages(transport_name: str = "grpc"): +def test_list_audit_reports_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="abc", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[], - next_page_token="def", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="ghi", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - ), - RuntimeError, - ) - pages = list(client.list_resource_enrollment_statuses(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_resource_enrollment_statuses_async_pager(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = auditmanager.ListAuditReportsRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_audit_reports), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="abc", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[], - next_page_token="def", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="ghi", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - async_pager = await client.list_resource_enrollment_statuses( - request={}, + client.list_audit_reports(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListAuditReportsRequest( + parent="parent_value", + page_token="page_token_value", ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + assert args[0] == request_msg - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - assert len(responses) == 6 - assert all( - isinstance(i, auditmanager.ResourceEnrollmentStatus) for i in responses - ) - - -@pytest.mark.asyncio -async def test_list_resource_enrollment_statuses_async_pages(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="abc", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[], - next_page_token="def", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="ghi", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.list_resource_enrollment_statuses(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - auditmanager.ListControlsRequest(), - {}, - ], -) -def test_list_controls(request_type, transport: str = "grpc"): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListControlsResponse( - next_page_token="next_page_token_value", - ) - response = client.list_controls(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = auditmanager.ListControlsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_controls_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = auditmanager.ListControlsRequest( - parent="parent_value", - page_token="page_token_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_controls(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListControlsRequest( - parent="parent_value", - page_token="page_token_value", - ) - assert args[0] == request_msg - - -def test_list_controls_use_cached_wrapped_rpc(): +def test_list_audit_reports_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4072,21 +3956,25 @@ def test_list_controls_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_controls in client._transport._wrapped_methods + assert ( + client._transport.list_audit_reports in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc + client._transport._wrapped_methods[client._transport.list_audit_reports] = ( + mock_rpc + ) request = {} - client.list_controls(request) + client.list_audit_reports(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_controls(request) + client.list_audit_reports(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4094,7 +3982,7 @@ def test_list_controls_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_controls_async_use_cached_wrapped_rpc( +async def test_list_audit_reports_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4111,7 +3999,7 @@ async def test_list_controls_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_controls + client._client._transport.list_audit_reports in client._client._transport._wrapped_methods ) @@ -4119,16 +4007,16 @@ async def test_list_controls_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_controls + client._client._transport.list_audit_reports ] = mock_rpc request = {} - await client.list_controls(request) + await client.list_audit_reports(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_controls(request) + await client.list_audit_reports(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4139,11 +4027,11 @@ async def test_list_controls_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - auditmanager.ListControlsRequest(), + auditmanager.ListAuditReportsRequest(), {}, ], ) -async def test_list_controls_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_audit_reports_async(request_type, transport: str = "grpc_asyncio"): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4154,41 +4042,45 @@ async def test_list_controls_async(request_type, transport: str = "grpc_asyncio" request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListControlsResponse( + auditmanager.ListAuditReportsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_controls(request) + response = await client.list_audit_reports(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = auditmanager.ListControlsRequest() + request = auditmanager.ListAuditReportsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsAsyncPager) + assert isinstance(response, pagers.ListAuditReportsAsyncPager) assert response.next_page_token == "next_page_token_value" -def test_list_controls_field_headers(): +def test_list_audit_reports_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.ListControlsRequest() + request = auditmanager.ListAuditReportsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - call.return_value = auditmanager.ListControlsResponse() - client.list_controls(request) + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: + call.return_value = auditmanager.ListAuditReportsResponse() + client.list_audit_reports(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4204,23 +4096,25 @@ def test_list_controls_field_headers(): @pytest.mark.asyncio -async def test_list_controls_field_headers_async(): +async def test_list_audit_reports_field_headers_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = auditmanager.ListControlsRequest() + request = auditmanager.ListAuditReportsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListControlsResponse() + auditmanager.ListAuditReportsResponse() ) - await client.list_controls(request) + await client.list_audit_reports(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4235,18 +4129,20 @@ async def test_list_controls_field_headers_async(): ) in kw["metadata"] -def test_list_controls_flattened(): +def test_list_audit_reports_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListControlsResponse() + call.return_value = auditmanager.ListAuditReportsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_controls( + client.list_audit_reports( parent="parent_value", ) @@ -4259,7 +4155,7 @@ def test_list_controls_flattened(): assert arg == mock_val -def test_list_controls_flattened_error(): +def test_list_audit_reports_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4267,29 +4163,31 @@ def test_list_controls_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_controls( - auditmanager.ListControlsRequest(), + client.list_audit_reports( + auditmanager.ListAuditReportsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_controls_flattened_async(): +async def test_list_audit_reports_flattened_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = auditmanager.ListControlsResponse() + call.return_value = auditmanager.ListAuditReportsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListControlsResponse() + auditmanager.ListAuditReportsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_controls( + response = await client.list_audit_reports( parent="parent_value", ) @@ -4303,7 +4201,7 @@ async def test_list_controls_flattened_async(): @pytest.mark.asyncio -async def test_list_controls_flattened_error_async(): +async def test_list_audit_reports_flattened_error_async(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4311,44 +4209,46 @@ async def test_list_controls_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_controls( - auditmanager.ListControlsRequest(), + await client.list_audit_reports( + auditmanager.ListAuditReportsRequest(), parent="parent_value", ) -def test_list_controls_pager(transport_name: str = "grpc"): +def test_list_audit_reports_pager(transport_name: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], next_page_token="abc", ), - auditmanager.ListControlsResponse( - controls=[], + auditmanager.ListAuditReportsResponse( + audit_reports=[], next_page_token="def", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), ], next_page_token="ghi", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], ), RuntimeError, @@ -4360,7 +4260,7 @@ def test_list_controls_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_controls(request={}, retry=retry, timeout=timeout) + pager = client.list_audit_reports(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -4371,89 +4271,93 @@ def test_list_controls_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, auditmanager.Control) for i in results) + assert all(isinstance(i, auditmanager.AuditReport) for i in results) -def test_list_controls_pages(transport_name: str = "grpc"): +def test_list_audit_reports_pages(transport_name: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], next_page_token="abc", ), - auditmanager.ListControlsResponse( - controls=[], + auditmanager.ListAuditReportsResponse( + audit_reports=[], next_page_token="def", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), ], next_page_token="ghi", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], ), RuntimeError, ) - pages = list(client.list_controls(request={}).pages) + pages = list(client.list_audit_reports(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_controls_async_pager(): +async def test_list_audit_reports_async_pager(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_controls), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_audit_reports), + "__call__", + new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], next_page_token="abc", ), - auditmanager.ListControlsResponse( - controls=[], + auditmanager.ListAuditReportsResponse( + audit_reports=[], next_page_token="def", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), ], next_page_token="ghi", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], ), RuntimeError, ) - async_pager = await client.list_controls( + async_pager = await client.list_audit_reports( request={}, ) assert async_pager.next_page_token == "abc" @@ -4464,61 +4368,143 @@ async def test_list_controls_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, auditmanager.Control) for i in responses) + assert all(isinstance(i, auditmanager.AuditReport) for i in responses) @pytest.mark.asyncio -async def test_list_controls_async_pages(): +async def test_list_audit_reports_async_pages(): client = AuditManagerAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_controls), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_audit_reports), + "__call__", + new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], next_page_token="abc", ), - auditmanager.ListControlsResponse( - controls=[], + auditmanager.ListAuditReportsResponse( + audit_reports=[], next_page_token="def", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), ], next_page_token="ghi", ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), ], ), RuntimeError, ) pages = [] - async for page_ in (await client.list_controls(request={})).pages: + async for page_ in (await client.list_audit_reports(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_enroll_resource_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.GetAuditReportRequest(), + {}, + ], +) +def test_get_audit_report(request_type, transport: str = "grpc"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.AuditReport( + name="name_value", + operation_id="operation_id_value", + compliance_standard="compliance_standard_value", + scope="scope_value", + report_generation_state=auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS, + compliance_framework="compliance_framework_value", + scope_id="scope_id_value", + ) + response = client.get_audit_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = auditmanager.GetAuditReportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, auditmanager.AuditReport) + assert response.name == "name_value" + assert response.operation_id == "operation_id_value" + assert response.compliance_standard == "compliance_standard_value" + assert response.scope == "scope_value" + assert ( + response.report_generation_state + == auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS + ) + assert response.compliance_framework == "compliance_framework_value" + assert response.scope_id == "scope_id_value" + + +def test_get_audit_report_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = auditmanager.GetAuditReportRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_audit_report(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetAuditReportRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_audit_report_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4526,362 +4512,353 @@ def test_enroll_resource_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.enroll_resource in client._transport._wrapped_methods + assert client._transport.get_audit_report in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.enroll_resource] = mock_rpc - + client._transport._wrapped_methods[client._transport.get_audit_report] = ( + mock_rpc + ) request = {} - client.enroll_resource(request) + client.get_audit_report(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.enroll_resource(request) + client.get_audit_report(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_enroll_resource_rest_required_fields( - request_type=auditmanager.EnrollResourceRequest, +@pytest.mark.asyncio +async def test_get_audit_report_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.AuditManagerRestTransport - - request_init = {} - request_init["scope"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - default_values = getattr( - transport_class._BaseEnrollResource, - "_BaseEnrollResource__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.get_audit_report + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_audit_report + ] = mock_rpc - jsonified_request["scope"] = "scope_value" + request = {} + await client.get_audit_report(request) - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == "scope_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.get_audit_report(request) - # Designate an appropriate value for the returned response. - return_value = auditmanager.Enrollment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.Enrollment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.GetAuditReportRequest(), + {}, + ], +) +async def test_get_audit_report_async(request_type, transport: str = "grpc_asyncio"): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response = client.enroll_resource(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditReport( + name="name_value", + operation_id="operation_id_value", + compliance_standard="compliance_standard_value", + scope="scope_value", + report_generation_state=auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS, + compliance_framework="compliance_framework_value", + scope_id="scope_id_value", + ) + ) + response = await client.get_audit_report(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = auditmanager.GetAuditReportRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, auditmanager.AuditReport) + assert response.name == "name_value" + assert response.operation_id == "operation_id_value" + assert response.compliance_standard == "compliance_standard_value" + assert response.scope == "scope_value" + assert ( + response.report_generation_state + == auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS + ) + assert response.compliance_framework == "compliance_framework_value" + assert response.scope_id == "scope_id_value" -def test_enroll_resource_rest_flattened(): + +def test_get_audit_report_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = auditmanager.Enrollment() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.GetAuditReportRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"scope": "folders/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - scope="scope_value", - destinations=[ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + call.return_value = auditmanager.AuditReport() + client.get_audit_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_audit_report_field_headers_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.GetAuditReportRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditReport() ) - mock_args.update(sample_request) + await client.get_audit_report(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.Enrollment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.enroll_resource(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_audit_report_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.AuditReport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_audit_report( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{scope=folders/*/locations/*}:enrollResource" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_enroll_resource_rest_flattened_error(transport: str = "rest"): +def test_get_audit_report_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.enroll_resource( - auditmanager.EnrollResourceRequest(), - scope="scope_value", - destinations=[ - auditmanager.EnrollResourceRequest.EligibleDestination( - eligible_gcs_bucket="eligible_gcs_bucket_value" - ) - ], + client.get_audit_report( + auditmanager.GetAuditReportRequest(), + name="name_value", ) -def test_generate_audit_scope_report_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_get_audit_report_flattened_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.AuditReport() - # Ensure method has been cached - assert ( - client._transport.generate_audit_scope_report - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditReport() ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_audit_report( + name="name_value", ) - client._transport._wrapped_methods[ - client._transport.generate_audit_scope_report - ] = mock_rpc - - request = {} - client.generate_audit_scope_report(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.generate_audit_scope_report(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_audit_scope_report_rest_required_fields( - request_type=auditmanager.GenerateAuditScopeReportRequest, -): - transport_class = transports.AuditManagerRestTransport - - request_init = {} - request_init["scope"] = "" - request_init["compliance_framework"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseGenerateAuditScopeReport, - "_BaseGenerateAuditScopeReport__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_get_audit_report_flattened_error_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["scope"] = "scope_value" - jsonified_request["complianceFramework"] = "compliance_framework_value" + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_audit_report( + auditmanager.GetAuditReportRequest(), + name="name_value", + ) - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == "scope_value" - assert "complianceFramework" in jsonified_request - assert jsonified_request["complianceFramework"] == "compliance_framework_value" +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.GetResourceEnrollmentStatusRequest(), + {}, + ], +) +def test_get_resource_enrollment_status(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = auditmanager.AuditScopeReport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.AuditScopeReport.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ResourceEnrollmentStatus( + name="name_value", + enrolled=True, + display_name="display_name_value", + enrollment_state=auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED, + ) + response = client.get_resource_enrollment_status(request) - response = client.generate_audit_scope_report(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = auditmanager.GetResourceEnrollmentStatusRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert isinstance(response, auditmanager.ResourceEnrollmentStatus) + assert response.name == "name_value" + assert response.enrolled is True + assert response.display_name == "display_name_value" + assert ( + response.enrollment_state + == auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED + ) -def test_generate_audit_scope_report_rest_flattened(): +def test_get_resource_enrollment_status_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = auditmanager.AuditScopeReport() - - # get arguments that satisfy an http rule for this method - sample_request = {"scope": "folders/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - scope="scope_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.AuditScopeReport.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.generate_audit_scope_report(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{scope=folders/*/locations/*}/auditScopeReports:generate" - % client.transport._host, - args[1], - ) - - -def test_generate_audit_scope_report_rest_flattened_error(transport: str = "rest"): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = auditmanager.GetResourceEnrollmentStatusRequest( + name="name_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_audit_scope_report( - auditmanager.GenerateAuditScopeReportRequest(), - scope="scope_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_resource_enrollment_status(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetResourceEnrollmentStatusRequest( + name="name_value", ) + assert args[0] == request_msg -def test_generate_audit_report_rest_use_cached_wrapped_rpc(): +def test_get_resource_enrollment_status_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4890,7 +4867,7 @@ def test_generate_audit_report_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.generate_audit_report + client._transport.get_resource_enrollment_status in client._transport._wrapped_methods ) @@ -4899,768 +4876,899 @@ def test_generate_audit_report_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.generate_audit_report] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.get_resource_enrollment_status + ] = mock_rpc request = {} - client.generate_audit_report(request) + client.get_resource_enrollment_status(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.generate_audit_report(request) + client.get_resource_enrollment_status(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_generate_audit_report_rest_required_fields( - request_type=auditmanager.GenerateAuditReportRequest, +@pytest.mark.asyncio +async def test_get_resource_enrollment_status_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.AuditManagerRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["scope"] = "" - request_init["compliance_framework"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.get_resource_enrollment_status + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGenerateAuditReport, - "_BaseGenerateAuditReport__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_resource_enrollment_status + ] = mock_rpc + + request = {} + await client.get_resource_enrollment_status(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_resource_enrollment_status(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.GetResourceEnrollmentStatusRequest(), {}, + ], +) +async def test_get_resource_enrollment_status_async( + request_type, transport: str = "grpc_asyncio" +): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - jsonified_request["scope"] = "scope_value" - jsonified_request["complianceFramework"] = "compliance_framework_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ResourceEnrollmentStatus( + name="name_value", + enrolled=True, + display_name="display_name_value", + enrollment_state=auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED, + ) + ) + response = await client.get_resource_enrollment_status(request) - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == "scope_value" - assert "complianceFramework" in jsonified_request - assert jsonified_request["complianceFramework"] == "compliance_framework_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = auditmanager.GetResourceEnrollmentStatusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, auditmanager.ResourceEnrollmentStatus) + assert response.name == "name_value" + assert response.enrolled is True + assert response.display_name == "display_name_value" + assert ( + response.enrollment_state + == auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED + ) + +def test_get_resource_enrollment_status_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.GetResourceEnrollmentStatusRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + call.return_value = auditmanager.ResourceEnrollmentStatus() + client.get_resource_enrollment_status(request) - response = client.generate_audit_report(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_generate_audit_report_rest_flattened(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_resource_enrollment_status_field_headers_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.GetResourceEnrollmentStatusRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"scope": "folders/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - scope="scope_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ResourceEnrollmentStatus() ) - mock_args.update(sample_request) + await client.get_resource_enrollment_status(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.generate_audit_report(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_resource_enrollment_status_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ResourceEnrollmentStatus() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_enrollment_status( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{scope=folders/*/locations/*}/auditReports:generate" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_generate_audit_report_rest_flattened_error(transport: str = "rest"): +def test_get_resource_enrollment_status_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.generate_audit_report( - auditmanager.GenerateAuditReportRequest(), - scope="scope_value", - gcs_uri="gcs_uri_value", - compliance_standard="compliance_standard_value", - report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + client.get_resource_enrollment_status( + auditmanager.GetResourceEnrollmentStatusRequest(), + name="name_value", ) -def test_list_audit_reports_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_get_resource_enrollment_status_flattened_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ResourceEnrollmentStatus() - # Ensure method has been cached - assert ( - client._transport.list_audit_reports in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ResourceEnrollmentStatus() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_enrollment_status( + name="name_value", ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.list_audit_reports] = ( - mock_rpc - ) - - request = {} - client.list_audit_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_audit_reports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_audit_reports_rest_required_fields( - request_type=auditmanager.ListAuditReportsRequest, -): - transport_class = transports.AuditManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseListAuditReports, - "_BaseListAuditReports__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_get_resource_enrollment_status_flattened_error_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_resource_enrollment_status( + auditmanager.GetResourceEnrollmentStatusRequest(), + name="name_value", ) - ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.ListResourceEnrollmentStatusesRequest(), + {}, + ], +) +def test_list_resource_enrollment_statuses(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = auditmanager.ListAuditReportsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.ListAuditReportsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_resource_enrollment_statuses(request) - response = client.list_audit_reports(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = auditmanager.ListResourceEnrollmentStatusesRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceEnrollmentStatusesPager) + assert response.next_page_token == "next_page_token_value" -def test_list_audit_reports_rest_flattened(): +def test_list_resource_enrollment_statuses_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = auditmanager.ListAuditReportsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "organizations/sample1/locations/sample2"} + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = auditmanager.ListResourceEnrollmentStatusesRequest( + parent="parent_value", + page_token="page_token_value", + ) - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_resource_enrollment_statuses(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListResourceEnrollmentStatusesRequest( parent="parent_value", + page_token="page_token_value", ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.ListAuditReportsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_audit_reports(**mock_args) +def test_list_resource_enrollment_statuses_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=organizations/*/locations/*}/auditReports" - % client.transport._host, - args[1], + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_resource_enrollment_statuses + in client._transport._wrapped_methods ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_resource_enrollment_statuses + ] = mock_rpc + request = {} + client.list_resource_enrollment_statuses(request) -def test_list_audit_reports_rest_flattened_error(transport: str = "rest"): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_audit_reports( - auditmanager.ListAuditReportsRequest(), - parent="parent_value", + client.list_resource_enrollment_statuses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_resource_enrollment_statuses_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_list_audit_reports_rest_pager(transport: str = "rest"): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), - auditmanager.AuditReport(), - ], - next_page_token="abc", - ), - auditmanager.ListAuditReportsResponse( - audit_reports=[], - next_page_token="def", - ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - ], - next_page_token="ghi", - ), - auditmanager.ListAuditReportsResponse( - audit_reports=[ - auditmanager.AuditReport(), - auditmanager.AuditReport(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - auditmanager.ListAuditReportsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "organizations/sample1/locations/sample2"} - - pager = client.list_audit_reports(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, auditmanager.AuditReport) for i in results) - - pages = list(client.list_audit_reports(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_audit_report_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_audit_report in client._transport._wrapped_methods + # Ensure method has been cached + assert ( + client._client._transport.list_resource_enrollment_statuses + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_audit_report] = ( - mock_rpc - ) + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_resource_enrollment_statuses + ] = mock_rpc request = {} - client.get_audit_report(request) + await client.list_resource_enrollment_statuses(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_audit_report(request) + await client.list_resource_enrollment_statuses(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_audit_report_rest_required_fields( - request_type=auditmanager.GetAuditReportRequest, +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.ListResourceEnrollmentStatusesRequest(), + {}, + ], +) +async def test_list_resource_enrollment_statuses_async( + request_type, transport: str = "grpc_asyncio" ): - transport_class = transports.AuditManagerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - default_values = getattr( - transport_class._BaseGetAuditReport, - "_BaseGetAuditReport__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListResourceEnrollmentStatusesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_resource_enrollment_statuses(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = auditmanager.ListResourceEnrollmentStatusesRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceEnrollmentStatusesAsyncPager) + assert response.next_page_token == "next_page_token_value" - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_resource_enrollment_statuses_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = auditmanager.AuditReport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.ListResourceEnrollmentStatusesRequest() - # Convert return value to protobuf type - return_value = auditmanager.AuditReport.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + client.list_resource_enrollment_statuses(request) - response = client.get_audit_report(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_get_audit_report_rest_flattened(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_resource_enrollment_statuses_field_headers_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = auditmanager.AuditReport() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.ListResourceEnrollmentStatusesRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "folders/sample1/locations/sample2/auditReports/sample3" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListResourceEnrollmentStatusesResponse() ) - mock_args.update(sample_request) + await client.list_resource_enrollment_statuses(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.AuditReport.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_audit_report(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=folders/*/locations/*/auditReports/*}" - % client.transport._host, - args[1], + +def test_list_resource_enrollment_statuses_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_enrollment_statuses( + parent="parent_value", ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + -def test_get_audit_report_rest_flattened_error(transport: str = "rest"): +def test_list_resource_enrollment_statuses_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_audit_report( - auditmanager.GetAuditReportRequest(), - name="name_value", + client.list_resource_enrollment_statuses( + auditmanager.ListResourceEnrollmentStatusesRequest(), + parent="parent_value", ) -def test_get_resource_enrollment_status_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_list_resource_enrollment_statuses_flattened_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() - # Ensure method has been cached - assert ( - client._transport.get_resource_enrollment_status - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListResourceEnrollmentStatusesResponse() ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_enrollment_statuses( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.get_resource_enrollment_status - ] = mock_rpc - - request = {} - client.get_resource_enrollment_status(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_enrollment_status(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_resource_enrollment_status_rest_required_fields( - request_type=auditmanager.GetResourceEnrollmentStatusRequest, -): - transport_class = transports.AuditManagerRestTransport - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseGetResourceEnrollmentStatus, - "_BaseGetResourceEnrollmentStatus__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_list_resource_enrollment_statuses_flattened_error_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_resource_enrollment_statuses( + auditmanager.ListResourceEnrollmentStatusesRequest(), + parent="parent_value", + ) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_resource_enrollment_statuses_pager(transport_name: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = auditmanager.ResourceEnrollmentStatus() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="abc", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[], + next_page_token="def", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="ghi", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + ), + RuntimeError, + ) - # Convert return value to protobuf type - return_value = auditmanager.ResourceEnrollmentStatus.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_resource_enrollment_statuses( + request={}, retry=retry, timeout=timeout + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - response = client.get_resource_enrollment_status(request) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, auditmanager.ResourceEnrollmentStatus) for i in results + ) -def test_get_resource_enrollment_status_rest_flattened(): +def test_list_resource_enrollment_statuses_pages(transport_name: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = auditmanager.ResourceEnrollmentStatus() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/resourceEnrollmentStatuses/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.ResourceEnrollmentStatus.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_resource_enrollment_status(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/resourceEnrollmentStatuses/*}" - % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="abc", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[], + next_page_token="def", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="ghi", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + ), + RuntimeError, ) + pages = list(client.list_resource_enrollment_statuses(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_get_resource_enrollment_status_rest_flattened_error(transport: str = "rest"): +@pytest.mark.asyncio +async def test_list_resource_enrollment_statuses_async_pager(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="abc", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[], + next_page_token="def", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="ghi", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_enrollment_statuses( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, auditmanager.ResourceEnrollmentStatus) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_resource_enrollment_statuses_async_pages(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="abc", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[], + next_page_token="def", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="ghi", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_resource_enrollment_statuses(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.ListControlsRequest(), + {}, + ], +) +def test_list_controls(request_type, transport: str = "grpc"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_resource_enrollment_status( - auditmanager.GetResourceEnrollmentStatusRequest(), - name="name_value", + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ListControlsResponse( + next_page_token="next_page_token_value", ) + response = client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = auditmanager.ListControlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == "next_page_token_value" -def test_list_resource_enrollment_statuses_rest_use_cached_wrapped_rpc(): +def test_list_controls_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = auditmanager.ListControlsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_controls(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListControlsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_controls_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5668,252 +5776,447 @@ def test_list_resource_enrollment_statuses_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_resource_enrollment_statuses - in client._transport._wrapped_methods - ) + assert client._transport.list_controls in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_resource_enrollment_statuses - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc request = {} - client.list_resource_enrollment_statuses(request) + client.list_controls(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_resource_enrollment_statuses(request) + client.list_controls(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_resource_enrollment_statuses_rest_required_fields( - request_type=auditmanager.ListResourceEnrollmentStatusesRequest, +@pytest.mark.asyncio +async def test_list_controls_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.AuditManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - default_values = getattr( - transport_class._BaseListResourceEnrollmentStatuses, - "_BaseListResourceEnrollmentStatuses__REQUIRED_FIELDS_DEFAULT_VALUES", + # Ensure method has been cached + assert ( + client._client._transport.list_controls + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_controls + ] = mock_rpc + + request = {} + await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_controls(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.ListControlsRequest(), {}, + ], +) +async def test_list_controls_async(request_type, transport: str = "grpc_asyncio"): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListControlsResponse( + next_page_token="next_page_token_value", + ) ) - ) + response = await client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = auditmanager.ListControlsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsAsyncPager) + assert response.next_page_token == "next_page_token_value" - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_list_controls_field_headers(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = auditmanager.ListResourceEnrollmentStatusesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.ListControlsRequest() - # Convert return value to protobuf type - return_value = auditmanager.ListResourceEnrollmentStatusesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + call.return_value = auditmanager.ListControlsResponse() + client.list_controls(request) - response = client.list_resource_enrollment_statuses(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_list_resource_enrollment_statuses_rest_flattened(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_controls_field_headers_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = auditmanager.ListControlsRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "organizations/sample1/locations/sample2"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListControlsResponse() ) - mock_args.update(sample_request) + await client.list_controls(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = auditmanager.ListResourceEnrollmentStatusesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.list_resource_enrollment_statuses(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_controls_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ListControlsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_controls( + parent="parent_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=organizations/*/locations/*}/resourceEnrollmentStatuses" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_list_resource_enrollment_statuses_rest_flattened_error( - transport: str = "rest", -): +def test_list_controls_flattened_error(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_resource_enrollment_statuses( - auditmanager.ListResourceEnrollmentStatusesRequest(), + client.list_controls( + auditmanager.ListControlsRequest(), parent="parent_value", ) -def test_list_resource_enrollment_statuses_rest_pager(transport: str = "rest"): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_controls_flattened_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="abc", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[], - next_page_token="def", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - ], - next_page_token="ghi", - ), - auditmanager.ListResourceEnrollmentStatusesResponse( - resource_enrollment_statuses=[ - auditmanager.ResourceEnrollmentStatus(), - auditmanager.ResourceEnrollmentStatus(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = auditmanager.ListControlsResponse() - # Wrap the values into proper Response objs - response = tuple( - auditmanager.ListResourceEnrollmentStatusesResponse.to_json(x) - for x in response + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListControlsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_controls( + parent="parent_value", ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {"parent": "organizations/sample1/locations/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - pager = client.list_resource_enrollment_statuses(request=sample_request) + +@pytest.mark.asyncio +async def test_list_controls_flattened_error_async(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_controls( + auditmanager.ListControlsRequest(), + parent="parent_value", + ) + + +def test_list_controls_pager(transport_name: str = "grpc"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + auditmanager.Control(), + ], + next_page_token="abc", + ), + auditmanager.ListControlsResponse( + controls=[], + next_page_token="def", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + ], + next_page_token="ghi", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_controls(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, auditmanager.ResourceEnrollmentStatus) for i in results + assert all(isinstance(i, auditmanager.Control) for i in results) + + +def test_list_controls_pages(transport_name: str = "grpc"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + auditmanager.Control(), + ], + next_page_token="abc", + ), + auditmanager.ListControlsResponse( + controls=[], + next_page_token="def", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + ], + next_page_token="ghi", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + ], + ), + RuntimeError, ) + pages = list(client.list_controls(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - pages = list( - client.list_resource_enrollment_statuses(request=sample_request).pages + +@pytest.mark.asyncio +async def test_list_controls_async_pager(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + auditmanager.Control(), + ], + next_page_token="abc", + ), + auditmanager.ListControlsResponse( + controls=[], + next_page_token="def", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + ], + next_page_token="ghi", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_controls( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, auditmanager.Control) for i in responses) + + +@pytest.mark.asyncio +async def test_list_controls_async_pages(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_controls), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + auditmanager.Control(), + ], + next_page_token="abc", + ), + auditmanager.ListControlsResponse( + controls=[], + next_page_token="def", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + ], + next_page_token="ghi", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_controls(request={})).pages: + pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_list_controls_rest_use_cached_wrapped_rpc(): +def test_create_audit_schedule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5927,35 +6230,41 @@ def test_list_controls_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_controls in client._transport._wrapped_methods + assert ( + client._transport.create_audit_schedule + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc + client._transport._wrapped_methods[client._transport.create_audit_schedule] = ( + mock_rpc + ) request = {} - client.list_controls(request) + client.create_audit_schedule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_controls(request) + client.create_audit_schedule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_controls_rest_required_fields( - request_type=auditmanager.ListControlsRequest, +def test_create_audit_schedule_rest_required_fields( + request_type=auditmanager.CreateAuditScheduleRequest, ): transport_class = transports.AuditManagerRestTransport request_init = {} request_init["parent"] = "" + request_init["audit_schedule_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5963,10 +6272,11 @@ def test_list_controls_rest_required_fields( ) # verify fields with default values are dropped + assert "auditScheduleId" not in jsonified_request default_values = getattr( - transport_class._BaseListControls, - "_BaseListControls__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateAuditSchedule, + "_BaseCreateAuditSchedule__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5975,20 +6285,25 @@ def test_list_controls_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "auditScheduleId" in jsonified_request + assert jsonified_request["auditScheduleId"] == request_init["audit_schedule_id"] jsonified_request["parent"] = "parent_value" + jsonified_request["auditScheduleId"] = "audit_schedule_id_value" # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "pageSize", - "pageToken", + "auditScheduleId", + "validateOnly", ) ) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "auditScheduleId" in jsonified_request + assert jsonified_request["auditScheduleId"] == "audit_schedule_id_value" client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5997,7 +6312,7 @@ def test_list_controls_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = auditmanager.ListControlsResponse() + return_value = auditmanager.AuditSchedule() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6009,30 +6324,37 @@ def test_list_controls_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = auditmanager.ListControlsResponse.pb(return_value) + return_value = auditmanager.AuditSchedule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_controls(request) + response = client.create_audit_schedule(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "auditScheduleId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_controls_rest_flattened(): +def test_create_audit_schedule_rest_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6041,16 +6363,16 @@ def test_list_controls_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = auditmanager.ListControlsResponse() + return_value = auditmanager.AuditSchedule() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "organizations/sample1/locations/sample2/standards/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + audit_schedule_id="audit_schedule_id_value", ) mock_args.update(sample_request) @@ -6058,26 +6380,26 @@ def test_list_controls_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = auditmanager.ListControlsResponse.pb(return_value) + return_value = auditmanager.AuditSchedule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_controls(**mock_args) + client.create_audit_schedule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=organizations/*/locations/*/standards/*}/controls" + "%s/v1/{parent=projects/*/locations/*}/auditSchedules" % client.transport._host, args[1], ) -def test_list_controls_rest_flattened_error(transport: str = "rest"): +def test_create_audit_schedule_rest_flattened_error(transport: str = "rest"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6086,598 +6408,3761 @@ def test_list_controls_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_controls( - auditmanager.ListControlsRequest(), + client.create_audit_schedule( + auditmanager.CreateAuditScheduleRequest(), parent="parent_value", + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + audit_schedule_id="audit_schedule_id_value", ) -def test_list_controls_rest_pager(transport: str = "rest"): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), - auditmanager.Control(), - ], - next_page_token="abc", - ), - auditmanager.ListControlsResponse( - controls=[], - next_page_token="def", - ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - ], - next_page_token="ghi", - ), - auditmanager.ListControlsResponse( - controls=[ - auditmanager.Control(), - auditmanager.Control(), - ], - ), +def test_update_audit_schedule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple(auditmanager.ListControlsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - sample_request = { - "parent": "organizations/sample1/locations/sample2/standards/sample3" - } + # Ensure method has been cached + assert ( + client._transport.update_audit_schedule + in client._transport._wrapped_methods + ) - pager = client.list_controls(request=sample_request) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_audit_schedule] = ( + mock_rpc + ) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + request = {} + client.update_audit_schedule(request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, auditmanager.Control) for i in results) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - pages = list(client.list_controls(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.update_audit_schedule(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AuditManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.AuditManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuditManagerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) +def test_update_audit_schedule_rest_required_fields( + request_type=auditmanager.UpdateAuditScheduleRequest, +): + transport_class = transports.AuditManagerRestTransport - # It is an error to provide an api_key and a transport instance. - transport = transports.AuditManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AuditManagerClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AuditManagerClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # verify fields with default values are dropped - # It is an error to provide scopes and a transport instance. - transport = transports.AuditManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + default_values = getattr( + transport_class._BaseUpdateAuditSchedule, + "_BaseUpdateAuditSchedule__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) - with pytest.raises(ValueError): - client = AuditManagerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AuditManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "updateMask", + "validateOnly", + ) ) - client = AuditManagerClient(transport=transport) - assert client.transport is transport + # verify required fields with non-default values are left alone -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AuditManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AuditManagerGrpcAsyncIOTransport( + client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditSchedule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result -@pytest.mark.parametrize( - "transport_class", - [ - transports.AuditManagerGrpcTransport, - transports.AuditManagerGrpcAsyncIOTransport, - transports.AuditManagerRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.AuditSchedule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -def test_transport_kind_grpc(): - transport = AuditManagerClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_audit_schedule(request) -def test_initialize_client_w_grpc(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_enroll_resource_empty_call_grpc(): +def test_update_audit_schedule_rest_flattened(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: - call.return_value = auditmanager.Enrollment() - client.enroll_resource(request=None) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditSchedule() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.EnrollResourceRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "audit_schedule": { + "name": "projects/sample1/locations/sample2/auditSchedules/sample3" + } + } + # get truthy value for each flattened field + mock_args = dict( + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_audit_scope_report_empty_call_grpc(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.AuditSchedule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" - ) as call: - call.return_value = auditmanager.AuditScopeReport() - client.generate_audit_scope_report(request=None) + client.update_audit_schedule(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GenerateAuditScopeReportRequest() - assert args[0] == request_msg + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{audit_schedule.name=projects/*/locations/*/auditSchedules/*}" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_audit_report_empty_call_grpc(): +def test_update_audit_schedule_rest_flattened_error(transport: str = "rest"): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.generate_audit_report(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GenerateAuditReportRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_audit_schedule( + auditmanager.UpdateAuditScheduleRequest(), + audit_schedule=auditmanager.AuditSchedule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_audit_reports_empty_call_grpc(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_get_audit_schedule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" - ) as call: - call.return_value = auditmanager.ListAuditReportsResponse() - client.list_audit_reports(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListAuditReportsRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._transport.get_audit_schedule in client._transport._wrapped_methods + ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_audit_schedule] = ( + mock_rpc + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_audit_report_empty_call_grpc(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request = {} + client.get_audit_schedule(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: - call.return_value = auditmanager.AuditReport() - client.get_audit_report(request=None) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GetAuditReportRequest() - assert args[0] == request_msg + client.get_audit_schedule(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_resource_enrollment_status_empty_call_grpc(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" - ) as call: - call.return_value = auditmanager.ResourceEnrollmentStatus() - client.get_resource_enrollment_status(request=None) +def test_get_audit_schedule_rest_required_fields( + request_type=auditmanager.GetAuditScheduleRequest, +): + transport_class = transports.AuditManagerRestTransport - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GetResourceEnrollmentStatusRequest() - assert args[0] == request_msg + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_resource_enrollment_statuses_empty_call_grpc(): - client = AuditManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + default_values = getattr( + transport_class._BaseGetAuditSchedule, + "_BaseGetAuditSchedule__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" - ) as call: - call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() - client.list_resource_enrollment_statuses(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListResourceEnrollmentStatusesRequest() - assert args[0] == request_msg + jsonified_request["name"] = "name_value" + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_controls_empty_call_grpc(): client = AuditManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - call.return_value = auditmanager.ListControlsResponse() - client.list_controls(request=None) + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditSchedule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListControlsRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.AuditSchedule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -def test_transport_kind_grpc_asyncio(): - transport = AuditManagerAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_audit_schedule(request) -def test_initialize_client_w_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_enroll_resource_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_audit_schedule_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.Enrollment( - name="name_value", - ) - ) - await client.enroll_resource(request=None) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditSchedule() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.EnrollResourceRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/auditSchedules/sample3" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_audit_scope_report_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.AuditSchedule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_audit_scope_report), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditScopeReport( - name="name_value", - ) - ) - await client.generate_audit_scope_report(request=None) + client.get_audit_schedule(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GenerateAuditScopeReportRequest() - assert args[0] == request_msg + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/auditSchedules/*}" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_audit_report_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_audit_schedule_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_audit_report), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_audit_schedule( + auditmanager.GetAuditScheduleRequest(), + name="name_value", ) - await client.generate_audit_report(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GenerateAuditReportRequest() - assert args[0] == request_msg +def test_list_audit_schedules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_audit_reports_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_audit_reports), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListAuditReportsResponse( - next_page_token="next_page_token_value", - ) + # Ensure method has been cached + assert ( + client._transport.list_audit_schedules in client._transport._wrapped_methods ) - await client.list_audit_reports(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListAuditReportsRequest() - assert args[0] == request_msg + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_audit_schedules] = ( + mock_rpc + ) + request = {} + client.list_audit_schedules(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_audit_report_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_audit_schedules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_audit_schedules_rest_required_fields( + request_type=auditmanager.ListAuditSchedulesRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.AuditReport( - name="name_value", - operation_id="operation_id_value", - compliance_standard="compliance_standard_value", - scope="scope_value", - report_generation_state=auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS, - compliance_framework="compliance_framework_value", - scope_id="scope_id_value", - ) + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAuditSchedules, + "_BaseListAuditSchedules__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", ) - await client.get_audit_report(request=None) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GetAuditReportRequest() - assert args[0] == request_msg + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_resource_enrollment_status_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListAuditSchedulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.ListAuditSchedulesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_audit_schedules(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_audit_schedules_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_enrollment_status), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ResourceEnrollmentStatus( - name="name_value", - enrolled=True, - display_name="display_name_value", - enrollment_state=auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED, - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListAuditSchedulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - await client.get_resource_enrollment_status(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.GetResourceEnrollmentStatusRequest() - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.ListAuditSchedulesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_audit_schedules(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/auditSchedules" + % client.transport._host, + args[1], + ) + + +def test_list_audit_schedules_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_audit_schedules( + auditmanager.ListAuditSchedulesRequest(), + parent="parent_value", + ) + + +def test_list_audit_schedules_rest_pager(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), + ], + next_page_token="abc", + ), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[], + next_page_token="def", + ), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + ], + next_page_token="ghi", + ), + auditmanager.ListAuditSchedulesResponse( + audit_schedules=[ + auditmanager.AuditSchedule(), + auditmanager.AuditSchedule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + auditmanager.ListAuditSchedulesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_audit_schedules(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, auditmanager.AuditSchedule) for i in results) + + pages = list(client.list_audit_schedules(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_enroll_resource_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.enroll_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.enroll_resource] = mock_rpc + + request = {} + client.enroll_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.enroll_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_enroll_resource_rest_required_fields( + request_type=auditmanager.EnrollResourceRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["scope"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseEnrollResource, + "_BaseEnrollResource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scope"] = "scope_value" + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == "scope_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auditmanager.Enrollment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.Enrollment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.enroll_resource(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_enroll_resource_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.Enrollment() + + # get arguments that satisfy an http rule for this method + sample_request = {"scope": "folders/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + scope="scope_value", + destinations=[ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.Enrollment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.enroll_resource(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{scope=folders/*/locations/*}:enrollResource" + % client.transport._host, + args[1], + ) + + +def test_enroll_resource_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.enroll_resource( + auditmanager.EnrollResourceRequest(), + scope="scope_value", + destinations=[ + auditmanager.EnrollResourceRequest.EligibleDestination( + eligible_gcs_bucket="eligible_gcs_bucket_value" + ) + ], + ) + + +def test_generate_audit_scope_report_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_audit_scope_report + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.generate_audit_scope_report + ] = mock_rpc + + request = {} + client.generate_audit_scope_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_audit_scope_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_audit_scope_report_rest_required_fields( + request_type=auditmanager.GenerateAuditScopeReportRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["scope"] = "" + request_init["compliance_framework"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGenerateAuditScopeReport, + "_BaseGenerateAuditScopeReport__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scope"] = "scope_value" + jsonified_request["complianceFramework"] = "compliance_framework_value" + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == "scope_value" + assert "complianceFramework" in jsonified_request + assert jsonified_request["complianceFramework"] == "compliance_framework_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditScopeReport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.AuditScopeReport.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_audit_scope_report(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_generate_audit_scope_report_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditScopeReport() + + # get arguments that satisfy an http rule for this method + sample_request = {"scope": "folders/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + scope="scope_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.AuditScopeReport.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.generate_audit_scope_report(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{scope=folders/*/locations/*}/auditScopeReports:generate" + % client.transport._host, + args[1], + ) + + +def test_generate_audit_scope_report_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_audit_scope_report( + auditmanager.GenerateAuditScopeReportRequest(), + scope="scope_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditScopeReportRequest.AuditScopeReportFormat.AUDIT_SCOPE_REPORT_FORMAT_ODF, + ) + + +def test_generate_audit_report_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_audit_report + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_audit_report] = ( + mock_rpc + ) + + request = {} + client.generate_audit_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.generate_audit_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_audit_report_rest_required_fields( + request_type=auditmanager.GenerateAuditReportRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["scope"] = "" + request_init["compliance_framework"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGenerateAuditReport, + "_BaseGenerateAuditReport__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scope"] = "scope_value" + jsonified_request["complianceFramework"] = "compliance_framework_value" + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == "scope_value" + assert "complianceFramework" in jsonified_request + assert jsonified_request["complianceFramework"] == "compliance_framework_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_audit_report(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_generate_audit_report_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"scope": "folders/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + scope="scope_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.generate_audit_report(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{scope=folders/*/locations/*}/auditReports:generate" + % client.transport._host, + args[1], + ) + + +def test_generate_audit_report_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_audit_report( + auditmanager.GenerateAuditReportRequest(), + scope="scope_value", + gcs_uri="gcs_uri_value", + compliance_standard="compliance_standard_value", + report_format=auditmanager.GenerateAuditReportRequest.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + ) + + +def test_list_audit_reports_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_audit_reports in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_audit_reports] = ( + mock_rpc + ) + + request = {} + client.list_audit_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_audit_reports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_audit_reports_rest_required_fields( + request_type=auditmanager.ListAuditReportsRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAuditReports, + "_BaseListAuditReports__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListAuditReportsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.ListAuditReportsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_audit_reports(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_audit_reports_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListAuditReportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.ListAuditReportsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_audit_reports(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=organizations/*/locations/*}/auditReports" + % client.transport._host, + args[1], + ) + + +def test_list_audit_reports_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_audit_reports( + auditmanager.ListAuditReportsRequest(), + parent="parent_value", + ) + + +def test_list_audit_reports_rest_pager(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), + auditmanager.AuditReport(), + ], + next_page_token="abc", + ), + auditmanager.ListAuditReportsResponse( + audit_reports=[], + next_page_token="def", + ), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + ], + next_page_token="ghi", + ), + auditmanager.ListAuditReportsResponse( + audit_reports=[ + auditmanager.AuditReport(), + auditmanager.AuditReport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + auditmanager.ListAuditReportsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + pager = client.list_audit_reports(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, auditmanager.AuditReport) for i in results) + + pages = list(client.list_audit_reports(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_audit_report_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_audit_report in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_audit_report] = ( + mock_rpc + ) + + request = {} + client.get_audit_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_audit_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_audit_report_rest_required_fields( + request_type=auditmanager.GetAuditReportRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetAuditReport, + "_BaseGetAuditReport__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditReport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.AuditReport.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_audit_report(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_audit_report_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditReport() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "folders/sample1/locations/sample2/auditReports/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.AuditReport.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_audit_report(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=folders/*/locations/*/auditReports/*}" + % client.transport._host, + args[1], + ) + + +def test_get_audit_report_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_audit_report( + auditmanager.GetAuditReportRequest(), + name="name_value", + ) + + +def test_get_resource_enrollment_status_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_resource_enrollment_status + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_resource_enrollment_status + ] = mock_rpc + + request = {} + client.get_resource_enrollment_status(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_enrollment_status(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_resource_enrollment_status_rest_required_fields( + request_type=auditmanager.GetResourceEnrollmentStatusRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetResourceEnrollmentStatus, + "_BaseGetResourceEnrollmentStatus__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auditmanager.ResourceEnrollmentStatus() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.ResourceEnrollmentStatus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_resource_enrollment_status(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_resource_enrollment_status_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.ResourceEnrollmentStatus() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/resourceEnrollmentStatuses/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.ResourceEnrollmentStatus.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_resource_enrollment_status(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/resourceEnrollmentStatuses/*}" + % client.transport._host, + args[1], + ) + + +def test_get_resource_enrollment_status_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_resource_enrollment_status( + auditmanager.GetResourceEnrollmentStatusRequest(), + name="name_value", + ) + + +def test_list_resource_enrollment_statuses_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_resource_enrollment_statuses + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_resource_enrollment_statuses + ] = mock_rpc + + request = {} + client.list_resource_enrollment_statuses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_enrollment_statuses(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_resource_enrollment_statuses_rest_required_fields( + request_type=auditmanager.ListResourceEnrollmentStatusesRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListResourceEnrollmentStatuses, + "_BaseListResourceEnrollmentStatuses__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.ListResourceEnrollmentStatusesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_resource_enrollment_statuses(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_resource_enrollment_statuses_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.ListResourceEnrollmentStatusesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_resource_enrollment_statuses(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=organizations/*/locations/*}/resourceEnrollmentStatuses" + % client.transport._host, + args[1], + ) + + +def test_list_resource_enrollment_statuses_rest_flattened_error( + transport: str = "rest", +): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_resource_enrollment_statuses( + auditmanager.ListResourceEnrollmentStatusesRequest(), + parent="parent_value", + ) + + +def test_list_resource_enrollment_statuses_rest_pager(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="abc", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[], + next_page_token="def", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + ], + next_page_token="ghi", + ), + auditmanager.ListResourceEnrollmentStatusesResponse( + resource_enrollment_statuses=[ + auditmanager.ResourceEnrollmentStatus(), + auditmanager.ResourceEnrollmentStatus(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + auditmanager.ListResourceEnrollmentStatusesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + pager = client.list_resource_enrollment_statuses(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, auditmanager.ResourceEnrollmentStatus) for i in results + ) + + pages = list( + client.list_resource_enrollment_statuses(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_controls_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_controls in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc + + request = {} + client.list_controls(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_controls(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_controls_rest_required_fields( + request_type=auditmanager.ListControlsRequest, +): + transport_class = transports.AuditManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListControls, + "_BaseListControls__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListControlsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.ListControlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_controls(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_controls_rest_flattened(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListControlsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/locations/sample2/standards/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.ListControlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_controls(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=organizations/*/locations/*/standards/*}/controls" + % client.transport._host, + args[1], + ) + + +def test_list_controls_rest_flattened_error(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_controls( + auditmanager.ListControlsRequest(), + parent="parent_value", + ) + + +def test_list_controls_rest_pager(transport: str = "rest"): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + auditmanager.Control(), + ], + next_page_token="abc", + ), + auditmanager.ListControlsResponse( + controls=[], + next_page_token="def", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + ], + next_page_token="ghi", + ), + auditmanager.ListControlsResponse( + controls=[ + auditmanager.Control(), + auditmanager.Control(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(auditmanager.ListControlsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "organizations/sample1/locations/sample2/standards/sample3" + } + + pager = client.list_controls(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, auditmanager.Control) for i in results) + + pages = list(client.list_controls(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AuditManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AuditManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuditManagerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AuditManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AuditManagerClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AuditManagerClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AuditManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuditManagerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AuditManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AuditManagerClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AuditManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AuditManagerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuditManagerGrpcTransport, + transports.AuditManagerGrpcAsyncIOTransport, + transports.AuditManagerRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = AuditManagerClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_audit_schedule_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: + call.return_value = auditmanager.AuditSchedule() + client.create_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.CreateAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_audit_schedule_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_audit_schedule), "__call__" + ) as call: + call.return_value = auditmanager.AuditSchedule() + client.update_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.UpdateAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_audit_schedule_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_audit_schedule), "__call__" + ) as call: + call.return_value = auditmanager.AuditSchedule() + client.get_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_audit_schedules_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_audit_schedules), "__call__" + ) as call: + call.return_value = auditmanager.ListAuditSchedulesResponse() + client.list_audit_schedules(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListAuditSchedulesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_enroll_resource_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + call.return_value = auditmanager.Enrollment() + client.enroll_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.EnrollResourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_audit_scope_report_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_audit_scope_report), "__call__" + ) as call: + call.return_value = auditmanager.AuditScopeReport() + client.generate_audit_scope_report(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GenerateAuditScopeReportRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_audit_report_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_audit_report), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.generate_audit_report(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GenerateAuditReportRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_audit_reports_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: + call.return_value = auditmanager.ListAuditReportsResponse() + client.list_audit_reports(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListAuditReportsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_audit_report_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + call.return_value = auditmanager.AuditReport() + client.get_audit_report(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetAuditReportRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_resource_enrollment_status_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + call.return_value = auditmanager.ResourceEnrollmentStatus() + client.get_resource_enrollment_status(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetResourceEnrollmentStatusRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_resource_enrollment_statuses_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + call.return_value = auditmanager.ListResourceEnrollmentStatusesResponse() + client.list_resource_enrollment_statuses(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListResourceEnrollmentStatusesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_controls_empty_call_grpc(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + call.return_value = auditmanager.ListControlsResponse() + client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListControlsRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AuditManagerAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_audit_schedule_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) + ) + await client.create_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.CreateAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_audit_schedule_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_audit_schedule), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) + ) + await client.update_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.UpdateAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_audit_schedule_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_audit_schedule), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) + ) + await client.get_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_audit_schedules_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_audit_schedules), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListAuditSchedulesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_audit_schedules(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListAuditSchedulesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_enroll_resource_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.enroll_resource), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.Enrollment( + name="name_value", + ) + ) + await client.enroll_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.EnrollResourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_audit_scope_report_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_audit_scope_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditScopeReport( + name="name_value", + ) + ) + await client.generate_audit_scope_report(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GenerateAuditScopeReportRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_audit_report_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_audit_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.generate_audit_report(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GenerateAuditReportRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_audit_reports_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_audit_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListAuditReportsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_audit_reports(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListAuditReportsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_audit_report_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_audit_report), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.AuditReport( + name="name_value", + operation_id="operation_id_value", + compliance_standard="compliance_standard_value", + scope="scope_value", + report_generation_state=auditmanager.AuditReport.ReportGenerationState.IN_PROGRESS, + compliance_framework="compliance_framework_value", + scope_id="scope_id_value", + ) + ) + await client.get_audit_report(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetAuditReportRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_resource_enrollment_status_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_enrollment_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ResourceEnrollmentStatus( + name="name_value", + enrolled=True, + display_name="display_name_value", + enrollment_state=auditmanager.ResourceEnrollmentStatus.ResourceEnrollmentState.NOT_ENROLLED, + ) + ) + await client.get_resource_enrollment_status(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetResourceEnrollmentStatusRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_resource_enrollment_statuses_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_enrollment_statuses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListResourceEnrollmentStatusesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_resource_enrollment_statuses(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListResourceEnrollmentStatusesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_controls_empty_call_grpc_asyncio(): + client = AuditManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + auditmanager.ListControlsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListControlsRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AuditManagerClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_audit_schedule_rest_bad_request( + request_type=auditmanager.CreateAuditScheduleRequest, +): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_audit_schedule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.CreateAuditScheduleRequest, + dict, + ], +) +def test_create_audit_schedule_rest_call_success(request_type): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["audit_schedule"] = { + "name": "name_value", + "display_name": "display_name_value", + "gcs_uri": "gcs_uri_value", + "compliance_framework": "compliance_framework_value", + "report_format": 1, + "schedule_config": { + "start_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + "frequency": 1, + "time_zone": "time_zone_value", + }, + "state": 1, + "create_time": {}, + "update_time": {}, + "next_run_time": {}, + "last_trigger_time": {}, + "error_message": "error_message_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = auditmanager.CreateAuditScheduleRequest.meta.fields["audit_schedule"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["audit_schedule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["audit_schedule"][field])): + del request_init["audit_schedule"][field][i][subfield] + else: + del request_init["audit_schedule"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.AuditSchedule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_audit_schedule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, auditmanager.AuditSchedule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_audit_schedule_rest_interceptors(null_interceptor): + transport = transports.AuditManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AuditManagerRestInterceptor(), + ) + client = AuditManagerClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AuditManagerRestInterceptor, "post_create_audit_schedule" + ) as post, + mock.patch.object( + transports.AuditManagerRestInterceptor, + "post_create_audit_schedule_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AuditManagerRestInterceptor, "pre_create_audit_schedule" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = auditmanager.CreateAuditScheduleRequest.pb( + auditmanager.CreateAuditScheduleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = auditmanager.AuditSchedule.to_json(auditmanager.AuditSchedule()) + req.return_value.content = return_value + + request = auditmanager.CreateAuditScheduleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = auditmanager.AuditSchedule() + post_with_metadata.return_value = auditmanager.AuditSchedule(), metadata + + client.create_audit_schedule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_audit_schedule_rest_bad_request( + request_type=auditmanager.UpdateAuditScheduleRequest, +): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "audit_schedule": { + "name": "projects/sample1/locations/sample2/auditSchedules/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_audit_schedule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.UpdateAuditScheduleRequest, + dict, + ], +) +def test_update_audit_schedule_rest_call_success(request_type): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "audit_schedule": { + "name": "projects/sample1/locations/sample2/auditSchedules/sample3" + } + } + request_init["audit_schedule"] = { + "name": "projects/sample1/locations/sample2/auditSchedules/sample3", + "display_name": "display_name_value", + "gcs_uri": "gcs_uri_value", + "compliance_framework": "compliance_framework_value", + "report_format": 1, + "schedule_config": { + "start_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + "frequency": 1, + "time_zone": "time_zone_value", + }, + "state": 1, + "create_time": {}, + "update_time": {}, + "next_run_time": {}, + "last_trigger_time": {}, + "error_message": "error_message_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = auditmanager.UpdateAuditScheduleRequest.meta.fields["audit_schedule"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["audit_schedule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["audit_schedule"][field])): + del request_init["audit_schedule"][field][i][subfield] + else: + del request_init["audit_schedule"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.AuditSchedule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_audit_schedule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, auditmanager.AuditSchedule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_audit_schedule_rest_interceptors(null_interceptor): + transport = transports.AuditManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AuditManagerRestInterceptor(), + ) + client = AuditManagerClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AuditManagerRestInterceptor, "post_update_audit_schedule" + ) as post, + mock.patch.object( + transports.AuditManagerRestInterceptor, + "post_update_audit_schedule_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AuditManagerRestInterceptor, "pre_update_audit_schedule" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = auditmanager.UpdateAuditScheduleRequest.pb( + auditmanager.UpdateAuditScheduleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = auditmanager.AuditSchedule.to_json(auditmanager.AuditSchedule()) + req.return_value.content = return_value + + request = auditmanager.UpdateAuditScheduleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = auditmanager.AuditSchedule() + post_with_metadata.return_value = auditmanager.AuditSchedule(), metadata + + client.update_audit_schedule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_audit_schedule_rest_bad_request( + request_type=auditmanager.GetAuditScheduleRequest, +): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/auditSchedules/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_audit_schedule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.GetAuditScheduleRequest, + dict, + ], +) +def test_get_audit_schedule_rest_call_success(request_type): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/auditSchedules/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.AuditSchedule( + name="name_value", + display_name="display_name_value", + gcs_uri="gcs_uri_value", + compliance_framework="compliance_framework_value", + report_format=auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF, + state=auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE, + error_message="error_message_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = auditmanager.AuditSchedule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_audit_schedule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, auditmanager.AuditSchedule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.gcs_uri == "gcs_uri_value" + assert response.compliance_framework == "compliance_framework_value" + assert ( + response.report_format + == auditmanager.AuditSchedule.AuditReportFormat.AUDIT_REPORT_FORMAT_ODF + ) + assert response.state == auditmanager.ScheduleState.SCHEDULE_STATE_ACTIVE + assert response.error_message == "error_message_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_audit_schedule_rest_interceptors(null_interceptor): + transport = transports.AuditManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AuditManagerRestInterceptor(), + ) + client = AuditManagerClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AuditManagerRestInterceptor, "post_get_audit_schedule" + ) as post, + mock.patch.object( + transports.AuditManagerRestInterceptor, + "post_get_audit_schedule_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AuditManagerRestInterceptor, "pre_get_audit_schedule" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = auditmanager.GetAuditScheduleRequest.pb( + auditmanager.GetAuditScheduleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = auditmanager.AuditSchedule.to_json(auditmanager.AuditSchedule()) + req.return_value.content = return_value + + request = auditmanager.GetAuditScheduleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = auditmanager.AuditSchedule() + post_with_metadata.return_value = auditmanager.AuditSchedule(), metadata + + client.get_audit_schedule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_audit_schedules_rest_bad_request( + request_type=auditmanager.ListAuditSchedulesRequest, +): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_audit_schedules(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_resource_enrollment_statuses_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + auditmanager.ListAuditSchedulesRequest, + dict, + ], +) +def test_list_audit_schedules_rest_call_success(request_type): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_enrollment_statuses), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListResourceEnrollmentStatusesResponse( - next_page_token="next_page_token_value", - ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auditmanager.ListAuditSchedulesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - await client.list_resource_enrollment_statuses(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListResourceEnrollmentStatusesRequest() - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = auditmanager.ListAuditSchedulesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_audit_schedules(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_controls_empty_call_grpc_asyncio(): - client = AuditManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuditSchedulesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_audit_schedules_rest_interceptors(null_interceptor): + transport = transports.AuditManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AuditManagerRestInterceptor(), ) + client = AuditManagerClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - auditmanager.ListControlsResponse( - next_page_token="next_page_token_value", - ) + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AuditManagerRestInterceptor, "post_list_audit_schedules" + ) as post, + mock.patch.object( + transports.AuditManagerRestInterceptor, + "post_list_audit_schedules_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AuditManagerRestInterceptor, "pre_list_audit_schedules" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = auditmanager.ListAuditSchedulesRequest.pb( + auditmanager.ListAuditSchedulesRequest() ) - await client.list_controls(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = auditmanager.ListControlsRequest() - assert args[0] == request_msg + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = auditmanager.ListAuditSchedulesResponse.to_json( + auditmanager.ListAuditSchedulesResponse() + ) + req.return_value.content = return_value + request = auditmanager.ListAuditSchedulesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = auditmanager.ListAuditSchedulesResponse() + post_with_metadata.return_value = ( + auditmanager.ListAuditSchedulesResponse(), + metadata, + ) -def test_transport_kind_rest(): - transport = AuditManagerClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.list_audit_schedules( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() def test_enroll_resource_rest_bad_request( @@ -8157,6 +11642,90 @@ def test_initialize_client_w_rest(): assert client is not None +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_audit_schedule_empty_call_rest(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_audit_schedule), "__call__" + ) as call: + client.create_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.CreateAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_audit_schedule_empty_call_rest(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_audit_schedule), "__call__" + ) as call: + client.update_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.UpdateAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_audit_schedule_empty_call_rest(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_audit_schedule), "__call__" + ) as call: + client.get_audit_schedule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.GetAuditScheduleRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_audit_schedules_empty_call_rest(): + client = AuditManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_audit_schedules), "__call__" + ) as call: + client.list_audit_schedules(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = auditmanager.ListAuditSchedulesRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_enroll_resource_empty_call_rest(): @@ -8369,6 +11938,10 @@ def test_audit_manager_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( + "create_audit_schedule", + "update_audit_schedule", + "get_audit_schedule", + "list_audit_schedules", "enroll_resource", "generate_audit_scope_report", "generate_audit_report", @@ -8662,6 +12235,18 @@ def test_audit_manager_client_transport_session_collision(transport_name): credentials=creds2, transport=transport_name, ) + session1 = client1.transport.create_audit_schedule._session + session2 = client2.transport.create_audit_schedule._session + assert session1 != session2 + session1 = client1.transport.update_audit_schedule._session + session2 = client2.transport.update_audit_schedule._session + assert session1 != session2 + session1 = client1.transport.get_audit_schedule._session + session2 = client2.transport.get_audit_schedule._session + assert session1 != session2 + session1 = client1.transport.list_audit_schedules._session + session2 = client2.transport.list_audit_schedules._session + assert session1 != session2 session1 = client1.transport.enroll_resource._session session2 = client2.transport.enroll_resource._session assert session1 != session2 @@ -8869,10 +12454,36 @@ def test_parse_audit_report_path(): assert expected == actual -def test_audit_scope_report_path(): +def test_audit_schedule_path(): project = "cuttlefish" location = "mussel" - audit_scope_report = "winkle" + audit_schedule = "winkle" + expected = "projects/{project}/locations/{location}/auditSchedules/{audit_schedule}".format( + project=project, + location=location, + audit_schedule=audit_schedule, + ) + actual = AuditManagerClient.audit_schedule_path(project, location, audit_schedule) + assert expected == actual + + +def test_parse_audit_schedule_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "audit_schedule": "abalone", + } + path = AuditManagerClient.audit_schedule_path(**expected) + + # Check that the path construction is reversible. + actual = AuditManagerClient.parse_audit_schedule_path(path) + assert expected == actual + + +def test_audit_scope_report_path(): + project = "squid" + location = "clam" + audit_scope_report = "whelk" expected = "projects/{project}/locations/{location}/auditScopeReports/{audit_scope_report}".format( project=project, location=location, @@ -8886,9 +12497,9 @@ def test_audit_scope_report_path(): def test_parse_audit_scope_report_path(): expected = { - "project": "nautilus", - "location": "scallop", - "audit_scope_report": "abalone", + "project": "octopus", + "location": "oyster", + "audit_scope_report": "nudibranch", } path = AuditManagerClient.audit_scope_report_path(**expected) @@ -8898,9 +12509,9 @@ def test_parse_audit_scope_report_path(): def test_enrollment_path(): - project = "squid" - location = "clam" - enrollment = "whelk" + project = "cuttlefish" + location = "mussel" + enrollment = "winkle" expected = ( "projects/{project}/locations/{location}/enrollments/{enrollment}".format( project=project, @@ -8914,9 +12525,9 @@ def test_enrollment_path(): def test_parse_enrollment_path(): expected = { - "project": "octopus", - "location": "oyster", - "enrollment": "nudibranch", + "project": "nautilus", + "location": "scallop", + "enrollment": "abalone", } path = AuditManagerClient.enrollment_path(**expected) @@ -8926,8 +12537,8 @@ def test_parse_enrollment_path(): def test_enrollment_status_scope_path(): - folder = "cuttlefish" - location = "mussel" + folder = "squid" + location = "clam" expected = "folders/{folder}/locations/{location}".format( folder=folder, location=location, @@ -8938,8 +12549,8 @@ def test_enrollment_status_scope_path(): def test_parse_enrollment_status_scope_path(): expected = { - "folder": "winkle", - "location": "nautilus", + "folder": "whelk", + "location": "octopus", } path = AuditManagerClient.enrollment_status_scope_path(**expected) @@ -8949,9 +12560,9 @@ def test_parse_enrollment_status_scope_path(): def test_resource_enrollment_status_path(): - folder = "scallop" - location = "abalone" - resource_enrollment_status = "squid" + folder = "oyster" + location = "nudibranch" + resource_enrollment_status = "cuttlefish" expected = "folders/{folder}/locations/{location}/resourceEnrollmentStatuses/{resource_enrollment_status}".format( folder=folder, location=location, @@ -8965,9 +12576,9 @@ def test_resource_enrollment_status_path(): def test_parse_resource_enrollment_status_path(): expected = { - "folder": "clam", - "location": "whelk", - "resource_enrollment_status": "octopus", + "folder": "mussel", + "location": "winkle", + "resource_enrollment_status": "nautilus", } path = AuditManagerClient.resource_enrollment_status_path(**expected) @@ -8977,9 +12588,9 @@ def test_parse_resource_enrollment_status_path(): def test_standard_path(): - project = "oyster" - location = "nudibranch" - standard = "cuttlefish" + project = "scallop" + location = "abalone" + standard = "squid" expected = "projects/{project}/locations/{location}/standards/{standard}".format( project=project, location=location, @@ -8991,9 +12602,9 @@ def test_standard_path(): def test_parse_standard_path(): expected = { - "project": "mussel", - "location": "winkle", - "standard": "nautilus", + "project": "clam", + "location": "whelk", + "standard": "octopus", } path = AuditManagerClient.standard_path(**expected) @@ -9003,7 +12614,7 @@ def test_parse_standard_path(): def test_common_billing_account_path(): - billing_account = "scallop" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -9013,7 +12624,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "nudibranch", } path = AuditManagerClient.common_billing_account_path(**expected) @@ -9023,7 +12634,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -9033,7 +12644,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "mussel", } path = AuditManagerClient.common_folder_path(**expected) @@ -9043,7 +12654,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -9053,7 +12664,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "nautilus", } path = AuditManagerClient.common_organization_path(**expected) @@ -9063,7 +12674,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -9073,7 +12684,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "abalone", } path = AuditManagerClient.common_project_path(**expected) @@ -9083,8 +12694,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -9095,8 +12706,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "whelk", + "location": "octopus", } path = AuditManagerClient.common_location_path(**expected) diff --git a/packages/google-cloud-backupdr/CHANGELOG.md b/packages/google-cloud-backupdr/CHANGELOG.md index 4b1c1ef2b3dc..3a842d7c6b00 100644 --- a/packages/google-cloud-backupdr/CHANGELOG.md +++ b/packages/google-cloud-backupdr/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-backupdr/#history +## [0.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-backupdr-v0.10.1...google-cloud-backupdr-v0.10.2) (2026-09-17) + + +### Features + +* **google/cloud/backupdr/v1beta:** add google-cloud-backupdr ([#18399](https://github.com/googleapis/google-cloud-python/issues/18399)) ([91b7ae7](https://github.com/googleapis/google-cloud-python/commit/91b7ae7ef0aaa626b58b0d00e1c7d4a247c7c126)) + ## [0.10.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-backupdr-v0.10.0...google-cloud-backupdr-v0.10.1) (2026-08-06) diff --git a/packages/google-cloud-backupdr/docs/backupdr_v1beta/backup_dr.rst b/packages/google-cloud-backupdr/docs/backupdr_v1beta/backup_dr.rst new file mode 100644 index 000000000000..b069e43dc810 --- /dev/null +++ b/packages/google-cloud-backupdr/docs/backupdr_v1beta/backup_dr.rst @@ -0,0 +1,10 @@ +BackupDR +-------------------------- + +.. automodule:: google.cloud.backupdr_v1beta.services.backup_dr + :members: + :inherited-members: + +.. automodule:: google.cloud.backupdr_v1beta.services.backup_dr.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-backupdr/docs/backupdr_v1beta/backup_dr_protection_summary.rst b/packages/google-cloud-backupdr/docs/backupdr_v1beta/backup_dr_protection_summary.rst new file mode 100644 index 000000000000..70a24e94a497 --- /dev/null +++ b/packages/google-cloud-backupdr/docs/backupdr_v1beta/backup_dr_protection_summary.rst @@ -0,0 +1,10 @@ +BackupDrProtectionSummary +------------------------------------------- + +.. automodule:: google.cloud.backupdr_v1beta.services.backup_dr_protection_summary + :members: + :inherited-members: + +.. automodule:: google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-backupdr/docs/backupdr_v1beta/services_.rst b/packages/google-cloud-backupdr/docs/backupdr_v1beta/services_.rst new file mode 100644 index 000000000000..b4323062611e --- /dev/null +++ b/packages/google-cloud-backupdr/docs/backupdr_v1beta/services_.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Backupdr v1beta API +============================================= +.. toctree:: + :maxdepth: 2 + + backup_dr + backup_dr_protection_summary diff --git a/packages/google-cloud-backupdr/docs/backupdr_v1beta/types_.rst b/packages/google-cloud-backupdr/docs/backupdr_v1beta/types_.rst new file mode 100644 index 000000000000..6a43c17d10e9 --- /dev/null +++ b/packages/google-cloud-backupdr/docs/backupdr_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Backupdr v1beta API +========================================== + +.. automodule:: google.cloud.backupdr_v1beta.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-backupdr/docs/index.rst b/packages/google-cloud-backupdr/docs/index.rst index 54f18b02ce65..a8887ff229b5 100644 --- a/packages/google-cloud-backupdr/docs/index.rst +++ b/packages/google-cloud-backupdr/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Backup and DR Service. +By default, you will get version ``backupdr_v1``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference backupdr_v1/services_ backupdr_v1/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + backupdr_v1beta/services_ + backupdr_v1beta/types_ + Changelog --------- diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py b/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py index e946c8a43986..d0c6015ceaf2 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.1" # {x-release-please-version} +__version__ = "0.10.2" # {x-release-please-version} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py index e946c8a43986..d0c6015ceaf2 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.1" # {x-release-please-version} +__version__ = "0.10.2" # {x-release-please-version} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/__init__.py new file mode 100644 index 000000000000..932b3142187c --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/__init__.py @@ -0,0 +1,421 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import google.api_core as api_core + +from google.cloud.backupdr_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__ = { + "google.cloud.backupdr_v1beta.services.backup_dr", + "google.cloud.backupdr_v1beta.services.backup_dr_protection_summary", + "google.cloud.backupdr_v1beta.types.appliedautoprotectionpolicy", + "google.cloud.backupdr_v1beta.types.autoprotectionpolicy", + "google.cloud.backupdr_v1beta.types.autoprotectionpolicybinding", + "google.cloud.backupdr_v1beta.types.backupdr", + "google.cloud.backupdr_v1beta.types.backupplan", + "google.cloud.backupdr_v1beta.types.backupplanassociation", + "google.cloud.backupdr_v1beta.types.backupvault", + "google.cloud.backupdr_v1beta.types.backupvault_alloydb", + "google.cloud.backupdr_v1beta.types.backupvault_ba", + "google.cloud.backupdr_v1beta.types.backupvault_cloudsql", + "google.cloud.backupdr_v1beta.types.backupvault_disk", + "google.cloud.backupdr_v1beta.types.backupvault_gce", + "google.cloud.backupdr_v1beta.types.bindingmatchingresource", + "google.cloud.backupdr_v1beta.types.datasourcereference", + "google.cloud.backupdr_v1beta.types.protection_summary", +} + + +from .services.backup_dr import BackupDRAsyncClient, BackupDRClient +from .services.backup_dr_protection_summary import ( + BackupDrProtectionSummaryAsyncClient, + BackupDrProtectionSummaryClient, +) +from .types.appliedautoprotectionpolicy import ( + AppliedAutoProtectionPolicy, + ListAppliedAutoProtectionPoliciesRequest, + ListAppliedAutoProtectionPoliciesResponse, +) +from .types.autoprotectionpolicy import ( + AutoProtectionPolicy, + BackupPlanDetail, + BindingSummary, + CreateAutoProtectionPolicyRequest, + Criteria, + DeleteAutoProtectionPolicyRequest, + GetAutoProtectionPolicyRequest, + KeyValuePair, + ListAutoProtectionPoliciesRequest, + ListAutoProtectionPoliciesResponse, + MatchingCondition, + PolicyEvaluationSummary, + UpdateAutoProtectionPolicyRequest, +) +from .types.autoprotectionpolicybinding import ( + AutoProtectionPolicyBinding, + BindingEvaluationSummary, + CreateAutoProtectionPolicyBindingRequest, + GetAutoProtectionPolicyBindingRequest, + InitiateDeleteAutoProtectionPolicyBindingRequest, + ListAutoProtectionPolicyBindingsRequest, + ListAutoProtectionPolicyBindingsResponse, +) +from .types.backupdr import ( + CreateManagementServerRequest, + DeleteManagementServerRequest, + GetManagementServerRequest, + InitializeServiceRequest, + InitializeServiceResponse, + ListManagementServersRequest, + ListManagementServersResponse, + ManagementServer, + ManagementURI, + NetworkConfig, + OperationMetadata, + WorkforceIdentityBasedManagementURI, + WorkforceIdentityBasedOAuth2ClientID, +) +from .types.backupplan import ( + BackupPlan, + BackupPlanRevision, + BackupRule, + BackupWindow, + ComputeInstanceBackupPlanProperties, + CreateBackupPlanRequest, + DeleteBackupPlanRequest, + DiskBackupPlanProperties, + GetBackupPlanRequest, + GetBackupPlanRevisionRequest, + ListBackupPlanRevisionsRequest, + ListBackupPlanRevisionsResponse, + ListBackupPlansRequest, + ListBackupPlansResponse, + StandardSchedule, + UpdateBackupPlanRequest, + WeekDayOfMonth, +) +from .types.backupplanassociation import ( + BackupPlanAssociation, + CreateBackupPlanAssociationRequest, + DeleteBackupPlanAssociationRequest, + FetchBackupPlanAssociationsForResourceTypeRequest, + FetchBackupPlanAssociationsForResourceTypeResponse, + GetBackupPlanAssociationRequest, + ListBackupPlanAssociationsRequest, + ListBackupPlanAssociationsResponse, + RuleConfigInfo, + TriggerBackupRequest, + UpdateBackupPlanAssociationRequest, +) +from .types.backupvault import ( + Backup, + BackupApplianceBackupConfig, + BackupApplianceLockInfo, + BackupConfigInfo, + BackupConfigState, + BackupGcpResource, + BackupLock, + BackupVault, + BackupVaultView, + BackupView, + CreateBackupVaultRequest, + DataSource, + DataSourceBackupApplianceApplication, + DataSourceGcpResource, + DeleteBackupRequest, + DeleteBackupVaultRequest, + FetchBackupsForResourceTypeRequest, + FetchBackupsForResourceTypeResponse, + FetchUsableBackupVaultsRequest, + FetchUsableBackupVaultsResponse, + GcpBackupConfig, + GcpResource, + GetBackupRequest, + GetBackupVaultRequest, + GetDataSourceRequest, + ListBackupsRequest, + ListBackupsResponse, + ListBackupVaultsRequest, + ListBackupVaultsResponse, + ListDataSourcesRequest, + ListDataSourcesResponse, + RestoreBackupRequest, + RestoreBackupResponse, + ServiceLockInfo, + TargetResource, + UpdateBackupRequest, + UpdateBackupVaultRequest, + UpdateDataSourceRequest, +) +from .types.backupvault_alloydb import ( + AlloyDBClusterBackupPlanAssociationProperties, + AlloyDbClusterBackupProperties, + AlloyDBClusterDataSourceProperties, + AlloyDBClusterDataSourceReferenceProperties, + AlloyDbPitrWindow, +) +from .types.backupvault_ba import BackupApplianceBackupProperties +from .types.backupvault_cloudsql import ( + CloudSqlInstanceBackupPlanAssociationProperties, + CloudSqlInstanceBackupProperties, + CloudSqlInstanceDataSourceProperties, + CloudSqlInstanceDataSourceReferenceProperties, + CloudSqlInstanceInitializationConfig, +) +from .types.backupvault_disk import ( + DiskBackupProperties, + DiskDataSourceProperties, + DiskRestoreProperties, + DiskTargetEnvironment, + RegionDiskTargetEnvironment, + RestoreDiskFromInstanceOptions, +) +from .types.backupvault_gce import ( + AcceleratorConfig, + AccessConfig, + AdvancedMachineFeatures, + AliasIpRange, + AllocationAffinity, + AttachedDisk, + ComputeInstanceBackupProperties, + ComputeInstanceDataSourceProperties, + ComputeInstanceRestoreProperties, + ComputeInstanceTargetEnvironment, + ConfidentialInstanceConfig, + CustomerEncryptionKey, + DisplayDevice, + Entry, + GuestOsFeature, + InstanceParams, + KeyRevocationActionType, + Metadata, + NetworkInterface, + NetworkPerformanceConfig, + Scheduling, + SchedulingDuration, + ServiceAccount, + Tags, +) +from .types.bindingmatchingresource import ( + AutoProtectionDetails, + BindingMatchingResource, + GetBindingMatchingResourceRequest, + ListBindingMatchingResourcesRequest, + ListBindingMatchingResourcesResponse, +) +from .types.datasourcereference import ( + DataSourceBackupConfigInfo, + DataSourceGcpResourceInfo, + DataSourceReference, + FetchDataSourceReferencesForResourceTypeRequest, + FetchDataSourceReferencesForResourceTypeResponse, + GetDataSourceReferenceRequest, + ListDataSourceReferencesRequest, + ListDataSourceReferencesResponse, +) +from .types.protection_summary import ( + BackupConfigDetails, + BackupDrPlanConfig, + BackupDrPlanRule, + BackupDrTemplateConfig, + BackupLocation, + ListResourceBackupConfigsRequest, + ListResourceBackupConfigsResponse, + PitrSettings, + ResourceBackupConfig, +) + +__all__ = ( + "BackupDRAsyncClient", + "BackupDrProtectionSummaryAsyncClient", + "AcceleratorConfig", + "AccessConfig", + "AdvancedMachineFeatures", + "AliasIpRange", + "AllocationAffinity", + "AlloyDBClusterBackupPlanAssociationProperties", + "AlloyDBClusterDataSourceProperties", + "AlloyDBClusterDataSourceReferenceProperties", + "AlloyDbClusterBackupProperties", + "AlloyDbPitrWindow", + "AppliedAutoProtectionPolicy", + "AttachedDisk", + "AutoProtectionDetails", + "AutoProtectionPolicy", + "AutoProtectionPolicyBinding", + "Backup", + "BackupApplianceBackupConfig", + "BackupApplianceBackupProperties", + "BackupApplianceLockInfo", + "BackupConfigDetails", + "BackupConfigInfo", + "BackupConfigState", + "BackupDRClient", + "BackupDrPlanConfig", + "BackupDrPlanRule", + "BackupDrProtectionSummaryClient", + "BackupDrTemplateConfig", + "BackupGcpResource", + "BackupLocation", + "BackupLock", + "BackupPlan", + "BackupPlanAssociation", + "BackupPlanDetail", + "BackupPlanRevision", + "BackupRule", + "BackupVault", + "BackupVaultView", + "BackupView", + "BackupWindow", + "BindingEvaluationSummary", + "BindingMatchingResource", + "BindingSummary", + "CloudSqlInstanceBackupPlanAssociationProperties", + "CloudSqlInstanceBackupProperties", + "CloudSqlInstanceDataSourceProperties", + "CloudSqlInstanceDataSourceReferenceProperties", + "CloudSqlInstanceInitializationConfig", + "ComputeInstanceBackupPlanProperties", + "ComputeInstanceBackupProperties", + "ComputeInstanceDataSourceProperties", + "ComputeInstanceRestoreProperties", + "ComputeInstanceTargetEnvironment", + "ConfidentialInstanceConfig", + "CreateAutoProtectionPolicyBindingRequest", + "CreateAutoProtectionPolicyRequest", + "CreateBackupPlanAssociationRequest", + "CreateBackupPlanRequest", + "CreateBackupVaultRequest", + "CreateManagementServerRequest", + "Criteria", + "CustomerEncryptionKey", + "DataSource", + "DataSourceBackupApplianceApplication", + "DataSourceBackupConfigInfo", + "DataSourceGcpResource", + "DataSourceGcpResourceInfo", + "DataSourceReference", + "DeleteAutoProtectionPolicyRequest", + "DeleteBackupPlanAssociationRequest", + "DeleteBackupPlanRequest", + "DeleteBackupRequest", + "DeleteBackupVaultRequest", + "DeleteManagementServerRequest", + "DiskBackupPlanProperties", + "DiskBackupProperties", + "DiskDataSourceProperties", + "DiskRestoreProperties", + "DiskTargetEnvironment", + "DisplayDevice", + "Entry", + "FetchBackupPlanAssociationsForResourceTypeRequest", + "FetchBackupPlanAssociationsForResourceTypeResponse", + "FetchBackupsForResourceTypeRequest", + "FetchBackupsForResourceTypeResponse", + "FetchDataSourceReferencesForResourceTypeRequest", + "FetchDataSourceReferencesForResourceTypeResponse", + "FetchUsableBackupVaultsRequest", + "FetchUsableBackupVaultsResponse", + "GcpBackupConfig", + "GcpResource", + "GetAutoProtectionPolicyBindingRequest", + "GetAutoProtectionPolicyRequest", + "GetBackupPlanAssociationRequest", + "GetBackupPlanRequest", + "GetBackupPlanRevisionRequest", + "GetBackupRequest", + "GetBackupVaultRequest", + "GetBindingMatchingResourceRequest", + "GetDataSourceReferenceRequest", + "GetDataSourceRequest", + "GetManagementServerRequest", + "GuestOsFeature", + "InitializeServiceRequest", + "InitializeServiceResponse", + "InitiateDeleteAutoProtectionPolicyBindingRequest", + "InstanceParams", + "KeyRevocationActionType", + "KeyValuePair", + "ListAppliedAutoProtectionPoliciesRequest", + "ListAppliedAutoProtectionPoliciesResponse", + "ListAutoProtectionPoliciesRequest", + "ListAutoProtectionPoliciesResponse", + "ListAutoProtectionPolicyBindingsRequest", + "ListAutoProtectionPolicyBindingsResponse", + "ListBackupPlanAssociationsRequest", + "ListBackupPlanAssociationsResponse", + "ListBackupPlanRevisionsRequest", + "ListBackupPlanRevisionsResponse", + "ListBackupPlansRequest", + "ListBackupPlansResponse", + "ListBackupVaultsRequest", + "ListBackupVaultsResponse", + "ListBackupsRequest", + "ListBackupsResponse", + "ListBindingMatchingResourcesRequest", + "ListBindingMatchingResourcesResponse", + "ListDataSourceReferencesRequest", + "ListDataSourceReferencesResponse", + "ListDataSourcesRequest", + "ListDataSourcesResponse", + "ListManagementServersRequest", + "ListManagementServersResponse", + "ListResourceBackupConfigsRequest", + "ListResourceBackupConfigsResponse", + "ManagementServer", + "ManagementURI", + "MatchingCondition", + "Metadata", + "NetworkConfig", + "NetworkInterface", + "NetworkPerformanceConfig", + "OperationMetadata", + "PitrSettings", + "PolicyEvaluationSummary", + "RegionDiskTargetEnvironment", + "ResourceBackupConfig", + "RestoreBackupRequest", + "RestoreBackupResponse", + "RestoreDiskFromInstanceOptions", + "RuleConfigInfo", + "Scheduling", + "SchedulingDuration", + "ServiceAccount", + "ServiceLockInfo", + "StandardSchedule", + "Tags", + "TargetResource", + "TriggerBackupRequest", + "UpdateAutoProtectionPolicyRequest", + "UpdateBackupPlanAssociationRequest", + "UpdateBackupPlanRequest", + "UpdateBackupRequest", + "UpdateBackupVaultRequest", + "UpdateDataSourceRequest", + "WeekDayOfMonth", + "WorkforceIdentityBasedManagementURI", + "WorkforceIdentityBasedOAuth2ClientID", +) + +api_core.check_python_version("google.cloud.backupdr_v1beta") +api_core.check_dependency_versions("google.cloud.backupdr_v1beta") diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/_compat.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/_compat.py new file mode 100644 index 000000000000..3d3bdf9e2c91 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/_compat.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""A compatibility module for older versions of google-api-core.""" + +import json +import os +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import urlparse, urlunparse + +from google.api_core import path_template +from google.api_core.universe import EmptyUniverseError +from google.auth.exceptions import MutualTLSChannelError +from google.protobuf import json_format + +try: + # note: `#type: ignore` is added because the return type for `should_use_client_cert` + # is different than that of the fallback implementation below. This will be removed once + # we bump the minimum supported version of google-auth. + from google.auth.transport.mtls import should_use_client_cert # type: ignore +except ImportError: # pragma: NO COVER + + def should_use_client_cert(): + """Returns whether client certificate should be used for mTLS.""" + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert == "true" + + +def read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`," + " `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + +DEFAULT_UNIVERSE = "googleapis.com" + +try: + from google.api_core.universe import get_default_mtls_endpoint +except ImportError: # pragma: NO COVER + + def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Other URLs (including those that do not match these domain suffixes or + already contain '.mtls.') are passed through as-is. + + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint or ".mtls." in api_endpoint.lower(): + return api_endpoint + + has_scheme = "://" in api_endpoint + if not has_scheme: + parsed = urlparse("//" + api_endpoint) + else: + parsed = urlparse(api_endpoint) + + host = parsed.hostname + if not host: + return api_endpoint + + port = f":{parsed.port}" if parsed.port else "" + + lowered_host = host.lower() + suffix_sandbox = ".sandbox.googleapis.com" + suffix_google = ".googleapis.com" + if lowered_host.endswith(suffix_sandbox): + new_host = host[: -len(suffix_sandbox)] + ".mtls.sandbox.googleapis.com" + elif lowered_host.endswith(suffix_google): + new_host = host[: -len(suffix_google)] + ".mtls.googleapis.com" + else: + return api_endpoint + + netloc = new_host + port + new_parsed = parsed._replace(netloc=netloc) + + if not has_scheme: + return urlunparse(new_parsed)[2:] + else: + return urlunparse(new_parsed) + + +try: + from google.api_core.universe import get_api_endpoint +except ImportError: # pragma: NO COVER + + def get_api_endpoint( + api_override: Optional[str], + universe_domain: str, + default_universe: str, + default_mtls_endpoint: Optional[str], + default_endpoint_template: str, + use_mtls: bool, + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (Optional[str]): The API endpoint override. If specified, + this is always returned. + universe_domain (str): The universe domain used by the client. + default_universe (str): The default universe domain. + default_mtls_endpoint (Optional[str]): The default mTLS endpoint. + default_endpoint_template (str): The default endpoint template containing + a placeholder `{UNIVERSE_DOMAIN}`. + use_mtls (bool): Whether to use the mTLS endpoint. + + Returns: + str: The API endpoint to be used by the client. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mTLS is requested but + not supported in the configured universe domain. + ValueError: If mTLS is requested but no mTLS endpoint is available. + """ + if api_override is not None: + return api_override + + if use_mtls: + if universe_domain.lower() != default_universe.lower(): + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {default_universe}." + ) + if not default_mtls_endpoint: + raise ValueError("mTLS endpoint is not available.") + return default_mtls_endpoint + else: + return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + + +try: + from google.api_core.universe import get_universe_domain +except ImportError: # pragma: NO COVER + + def get_universe_domain( + *potential_universes: Optional[str], + default_universe: str, + ) -> str: + """Return the universe domain used by the client. + + Args: + *potential_universes (Optional[str]): Potential universe domains in order of preference. + default_universe (str): The default universe domain. + + Returns: + str: The universe domain to be used by the client. + + Raises: + EmptyUniverseError: If the resolved universe domain is an empty string. + """ + resolved = next( + (x.strip() for x in potential_universes if x is not None), + default_universe, + ) + + if not resolved: + raise EmptyUniverseError() + return resolved + + +try: + from google.api_core.rest_helpers import transcode_request # type: ignore +except ImportError: # pragma: NO COVER + + def transcode_request( + http_options: List[Dict[str, str]], + request: Any, + required_fields_default_values: Optional[Dict[str, Any]] = None, + rest_numeric_enums: bool = False, + ) -> Tuple[Dict[str, Any], Optional[str], Dict[str, Any]]: + """Transcodes a request into HTTP method, URI, body, and query parameters. + + Args: + http_options (List[Dict[str, str]]): List of HTTP transcoding rules. + request (Any): The protobuf or proto-plus request message. + required_fields_default_values (Optional[Dict[str, Any]]): Dictionary + of required fields default values to merge into query parameters if missing. + rest_numeric_enums (bool): Whether to encode enums as integers. + + Returns: + Tuple[Dict[str, Any], Optional[str], Dict[str, Any]]: A tuple containing: + - The raw transcoded request dictionary (containing keys like 'uri', 'method'). + - The serialized request body JSON string, or None if no body. + - The query parameters dictionary. + """ + if request is None: + raise TypeError("request cannot be None") + + # Convert proto-plus message to its underlying protobuf message if needed + pb_request = getattr(request, "_pb", request) + + transcoded_request = path_template.transcode(http_options, pb_request) + + body_json = None + if transcoded_request.get("body") is not None: + body_json = json_format.MessageToJson( + transcoded_request["body"], + use_integers_for_enums=rest_numeric_enums, + ) + + query_params_json = {} + if transcoded_request.get("query_params") is not None: + query_params_json = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=rest_numeric_enums, + ) + ) + + # If required_fields_default_values is provided, we merge default values for missing + # required fields into the query parameters. + if required_fields_default_values: + for k, v in required_fields_default_values.items(): + if k not in query_params_json: + query_params_json[k] = v + + if rest_numeric_enums: + query_params_json["$alt"] = "json;enum-encoding=int" + + return transcoded_request, body_json, query_params_json diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_metadata.json b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..2edda320fbff --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_metadata.json @@ -0,0 +1,797 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.backupdr_v1beta", + "protoPackage": "google.cloud.backupdr.v1beta", + "schema": "1.0", + "services": { + "BackupDR": { + "clients": { + "grpc": { + "libraryClient": "BackupDRClient", + "rpcs": { + "CreateAutoProtectionPolicy": { + "methods": [ + "create_auto_protection_policy" + ] + }, + "CreateAutoProtectionPolicyBinding": { + "methods": [ + "create_auto_protection_policy_binding" + ] + }, + "CreateBackupPlan": { + "methods": [ + "create_backup_plan" + ] + }, + "CreateBackupPlanAssociation": { + "methods": [ + "create_backup_plan_association" + ] + }, + "CreateBackupVault": { + "methods": [ + "create_backup_vault" + ] + }, + "CreateManagementServer": { + "methods": [ + "create_management_server" + ] + }, + "DeleteAutoProtectionPolicy": { + "methods": [ + "delete_auto_protection_policy" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteBackupPlan": { + "methods": [ + "delete_backup_plan" + ] + }, + "DeleteBackupPlanAssociation": { + "methods": [ + "delete_backup_plan_association" + ] + }, + "DeleteBackupVault": { + "methods": [ + "delete_backup_vault" + ] + }, + "DeleteManagementServer": { + "methods": [ + "delete_management_server" + ] + }, + "FetchBackupPlanAssociationsForResourceType": { + "methods": [ + "fetch_backup_plan_associations_for_resource_type" + ] + }, + "FetchBackupsForResourceType": { + "methods": [ + "fetch_backups_for_resource_type" + ] + }, + "FetchDataSourceReferencesForResourceType": { + "methods": [ + "fetch_data_source_references_for_resource_type" + ] + }, + "FetchUsableBackupVaults": { + "methods": [ + "fetch_usable_backup_vaults" + ] + }, + "GetAutoProtectionPolicy": { + "methods": [ + "get_auto_protection_policy" + ] + }, + "GetAutoProtectionPolicyBinding": { + "methods": [ + "get_auto_protection_policy_binding" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetBackupPlan": { + "methods": [ + "get_backup_plan" + ] + }, + "GetBackupPlanAssociation": { + "methods": [ + "get_backup_plan_association" + ] + }, + "GetBackupPlanRevision": { + "methods": [ + "get_backup_plan_revision" + ] + }, + "GetBackupVault": { + "methods": [ + "get_backup_vault" + ] + }, + "GetBindingMatchingResource": { + "methods": [ + "get_binding_matching_resource" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "GetDataSourceReference": { + "methods": [ + "get_data_source_reference" + ] + }, + "GetManagementServer": { + "methods": [ + "get_management_server" + ] + }, + "InitializeService": { + "methods": [ + "initialize_service" + ] + }, + "InitiateDeleteAutoProtectionPolicyBinding": { + "methods": [ + "initiate_delete_auto_protection_policy_binding" + ] + }, + "ListAppliedAutoProtectionPolicies": { + "methods": [ + "list_applied_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicies": { + "methods": [ + "list_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicyBindings": { + "methods": [ + "list_auto_protection_policy_bindings" + ] + }, + "ListBackupPlanAssociations": { + "methods": [ + "list_backup_plan_associations" + ] + }, + "ListBackupPlanRevisions": { + "methods": [ + "list_backup_plan_revisions" + ] + }, + "ListBackupPlans": { + "methods": [ + "list_backup_plans" + ] + }, + "ListBackupVaults": { + "methods": [ + "list_backup_vaults" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListBindingMatchingResources": { + "methods": [ + "list_binding_matching_resources" + ] + }, + "ListDataSourceReferences": { + "methods": [ + "list_data_source_references" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "ListManagementServers": { + "methods": [ + "list_management_servers" + ] + }, + "RestoreBackup": { + "methods": [ + "restore_backup" + ] + }, + "TriggerBackup": { + "methods": [ + "trigger_backup" + ] + }, + "UpdateAutoProtectionPolicy": { + "methods": [ + "update_auto_protection_policy" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateBackupPlan": { + "methods": [ + "update_backup_plan" + ] + }, + "UpdateBackupPlanAssociation": { + "methods": [ + "update_backup_plan_association" + ] + }, + "UpdateBackupVault": { + "methods": [ + "update_backup_vault" + ] + }, + "UpdateDataSource": { + "methods": [ + "update_data_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "BackupDRAsyncClient", + "rpcs": { + "CreateAutoProtectionPolicy": { + "methods": [ + "create_auto_protection_policy" + ] + }, + "CreateAutoProtectionPolicyBinding": { + "methods": [ + "create_auto_protection_policy_binding" + ] + }, + "CreateBackupPlan": { + "methods": [ + "create_backup_plan" + ] + }, + "CreateBackupPlanAssociation": { + "methods": [ + "create_backup_plan_association" + ] + }, + "CreateBackupVault": { + "methods": [ + "create_backup_vault" + ] + }, + "CreateManagementServer": { + "methods": [ + "create_management_server" + ] + }, + "DeleteAutoProtectionPolicy": { + "methods": [ + "delete_auto_protection_policy" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteBackupPlan": { + "methods": [ + "delete_backup_plan" + ] + }, + "DeleteBackupPlanAssociation": { + "methods": [ + "delete_backup_plan_association" + ] + }, + "DeleteBackupVault": { + "methods": [ + "delete_backup_vault" + ] + }, + "DeleteManagementServer": { + "methods": [ + "delete_management_server" + ] + }, + "FetchBackupPlanAssociationsForResourceType": { + "methods": [ + "fetch_backup_plan_associations_for_resource_type" + ] + }, + "FetchBackupsForResourceType": { + "methods": [ + "fetch_backups_for_resource_type" + ] + }, + "FetchDataSourceReferencesForResourceType": { + "methods": [ + "fetch_data_source_references_for_resource_type" + ] + }, + "FetchUsableBackupVaults": { + "methods": [ + "fetch_usable_backup_vaults" + ] + }, + "GetAutoProtectionPolicy": { + "methods": [ + "get_auto_protection_policy" + ] + }, + "GetAutoProtectionPolicyBinding": { + "methods": [ + "get_auto_protection_policy_binding" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetBackupPlan": { + "methods": [ + "get_backup_plan" + ] + }, + "GetBackupPlanAssociation": { + "methods": [ + "get_backup_plan_association" + ] + }, + "GetBackupPlanRevision": { + "methods": [ + "get_backup_plan_revision" + ] + }, + "GetBackupVault": { + "methods": [ + "get_backup_vault" + ] + }, + "GetBindingMatchingResource": { + "methods": [ + "get_binding_matching_resource" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "GetDataSourceReference": { + "methods": [ + "get_data_source_reference" + ] + }, + "GetManagementServer": { + "methods": [ + "get_management_server" + ] + }, + "InitializeService": { + "methods": [ + "initialize_service" + ] + }, + "InitiateDeleteAutoProtectionPolicyBinding": { + "methods": [ + "initiate_delete_auto_protection_policy_binding" + ] + }, + "ListAppliedAutoProtectionPolicies": { + "methods": [ + "list_applied_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicies": { + "methods": [ + "list_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicyBindings": { + "methods": [ + "list_auto_protection_policy_bindings" + ] + }, + "ListBackupPlanAssociations": { + "methods": [ + "list_backup_plan_associations" + ] + }, + "ListBackupPlanRevisions": { + "methods": [ + "list_backup_plan_revisions" + ] + }, + "ListBackupPlans": { + "methods": [ + "list_backup_plans" + ] + }, + "ListBackupVaults": { + "methods": [ + "list_backup_vaults" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListBindingMatchingResources": { + "methods": [ + "list_binding_matching_resources" + ] + }, + "ListDataSourceReferences": { + "methods": [ + "list_data_source_references" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "ListManagementServers": { + "methods": [ + "list_management_servers" + ] + }, + "RestoreBackup": { + "methods": [ + "restore_backup" + ] + }, + "TriggerBackup": { + "methods": [ + "trigger_backup" + ] + }, + "UpdateAutoProtectionPolicy": { + "methods": [ + "update_auto_protection_policy" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateBackupPlan": { + "methods": [ + "update_backup_plan" + ] + }, + "UpdateBackupPlanAssociation": { + "methods": [ + "update_backup_plan_association" + ] + }, + "UpdateBackupVault": { + "methods": [ + "update_backup_vault" + ] + }, + "UpdateDataSource": { + "methods": [ + "update_data_source" + ] + } + } + }, + "rest": { + "libraryClient": "BackupDRClient", + "rpcs": { + "CreateAutoProtectionPolicy": { + "methods": [ + "create_auto_protection_policy" + ] + }, + "CreateAutoProtectionPolicyBinding": { + "methods": [ + "create_auto_protection_policy_binding" + ] + }, + "CreateBackupPlan": { + "methods": [ + "create_backup_plan" + ] + }, + "CreateBackupPlanAssociation": { + "methods": [ + "create_backup_plan_association" + ] + }, + "CreateBackupVault": { + "methods": [ + "create_backup_vault" + ] + }, + "CreateManagementServer": { + "methods": [ + "create_management_server" + ] + }, + "DeleteAutoProtectionPolicy": { + "methods": [ + "delete_auto_protection_policy" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, + "DeleteBackupPlan": { + "methods": [ + "delete_backup_plan" + ] + }, + "DeleteBackupPlanAssociation": { + "methods": [ + "delete_backup_plan_association" + ] + }, + "DeleteBackupVault": { + "methods": [ + "delete_backup_vault" + ] + }, + "DeleteManagementServer": { + "methods": [ + "delete_management_server" + ] + }, + "FetchBackupPlanAssociationsForResourceType": { + "methods": [ + "fetch_backup_plan_associations_for_resource_type" + ] + }, + "FetchBackupsForResourceType": { + "methods": [ + "fetch_backups_for_resource_type" + ] + }, + "FetchDataSourceReferencesForResourceType": { + "methods": [ + "fetch_data_source_references_for_resource_type" + ] + }, + "FetchUsableBackupVaults": { + "methods": [ + "fetch_usable_backup_vaults" + ] + }, + "GetAutoProtectionPolicy": { + "methods": [ + "get_auto_protection_policy" + ] + }, + "GetAutoProtectionPolicyBinding": { + "methods": [ + "get_auto_protection_policy_binding" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetBackupPlan": { + "methods": [ + "get_backup_plan" + ] + }, + "GetBackupPlanAssociation": { + "methods": [ + "get_backup_plan_association" + ] + }, + "GetBackupPlanRevision": { + "methods": [ + "get_backup_plan_revision" + ] + }, + "GetBackupVault": { + "methods": [ + "get_backup_vault" + ] + }, + "GetBindingMatchingResource": { + "methods": [ + "get_binding_matching_resource" + ] + }, + "GetDataSource": { + "methods": [ + "get_data_source" + ] + }, + "GetDataSourceReference": { + "methods": [ + "get_data_source_reference" + ] + }, + "GetManagementServer": { + "methods": [ + "get_management_server" + ] + }, + "InitializeService": { + "methods": [ + "initialize_service" + ] + }, + "InitiateDeleteAutoProtectionPolicyBinding": { + "methods": [ + "initiate_delete_auto_protection_policy_binding" + ] + }, + "ListAppliedAutoProtectionPolicies": { + "methods": [ + "list_applied_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicies": { + "methods": [ + "list_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicyBindings": { + "methods": [ + "list_auto_protection_policy_bindings" + ] + }, + "ListBackupPlanAssociations": { + "methods": [ + "list_backup_plan_associations" + ] + }, + "ListBackupPlanRevisions": { + "methods": [ + "list_backup_plan_revisions" + ] + }, + "ListBackupPlans": { + "methods": [ + "list_backup_plans" + ] + }, + "ListBackupVaults": { + "methods": [ + "list_backup_vaults" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, + "ListBindingMatchingResources": { + "methods": [ + "list_binding_matching_resources" + ] + }, + "ListDataSourceReferences": { + "methods": [ + "list_data_source_references" + ] + }, + "ListDataSources": { + "methods": [ + "list_data_sources" + ] + }, + "ListManagementServers": { + "methods": [ + "list_management_servers" + ] + }, + "RestoreBackup": { + "methods": [ + "restore_backup" + ] + }, + "TriggerBackup": { + "methods": [ + "trigger_backup" + ] + }, + "UpdateAutoProtectionPolicy": { + "methods": [ + "update_auto_protection_policy" + ] + }, + "UpdateBackup": { + "methods": [ + "update_backup" + ] + }, + "UpdateBackupPlan": { + "methods": [ + "update_backup_plan" + ] + }, + "UpdateBackupPlanAssociation": { + "methods": [ + "update_backup_plan_association" + ] + }, + "UpdateBackupVault": { + "methods": [ + "update_backup_vault" + ] + }, + "UpdateDataSource": { + "methods": [ + "update_data_source" + ] + } + } + } + } + }, + "BackupDrProtectionSummary": { + "clients": { + "grpc": { + "libraryClient": "BackupDrProtectionSummaryClient", + "rpcs": { + "ListResourceBackupConfigs": { + "methods": [ + "list_resource_backup_configs" + ] + } + } + }, + "grpc-async": { + "libraryClient": "BackupDrProtectionSummaryAsyncClient", + "rpcs": { + "ListResourceBackupConfigs": { + "methods": [ + "list_resource_backup_configs" + ] + } + } + }, + "rest": { + "libraryClient": "BackupDrProtectionSummaryClient", + "rpcs": { + "ListResourceBackupConfigs": { + "methods": [ + "list_resource_backup_configs" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_version.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_version.py new file mode 100644 index 000000000000..d0c6015ceaf2 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.10.2" # {x-release-please-version} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/py.typed b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/py.typed new file mode 100644 index 000000000000..195a9f5c16ac --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-backupdr package uses inline types. diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/__init__.py new file mode 100644 index 000000000000..d39c4c41ee34 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import BackupDRAsyncClient +from .client import BackupDRClient + +__all__ = ( + "BackupDRClient", + "BackupDRAsyncClient", +) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/async_client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/async_client.py new file mode 100644 index 000000000000..9faa0fc739d4 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/async_client.py @@ -0,0 +1,7662 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.backupdr_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.backupdr_v1beta.services.backup_dr import pagers +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + backupvault_alloydb, + backupvault_ba, + backupvault_cloudsql, + backupvault_disk, + backupvault_gce, + bindingmatchingresource, + datasourcereference, +) + +from .client import BackupDRClient +from .transports.base import DEFAULT_CLIENT_INFO, BackupDRTransport +from .transports.grpc_asyncio import BackupDRGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class BackupDRAsyncClient: + """The BackupDR Service""" + + _client: BackupDRClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = BackupDRClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = BackupDRClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = BackupDRClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = BackupDRClient._DEFAULT_UNIVERSE + + applied_auto_protection_policy_path = staticmethod( + BackupDRClient.applied_auto_protection_policy_path + ) + parse_applied_auto_protection_policy_path = staticmethod( + BackupDRClient.parse_applied_auto_protection_policy_path + ) + auto_protection_policy_path = staticmethod( + BackupDRClient.auto_protection_policy_path + ) + parse_auto_protection_policy_path = staticmethod( + BackupDRClient.parse_auto_protection_policy_path + ) + auto_protection_policy_binding_path = staticmethod( + BackupDRClient.auto_protection_policy_binding_path + ) + parse_auto_protection_policy_binding_path = staticmethod( + BackupDRClient.parse_auto_protection_policy_binding_path + ) + backup_path = staticmethod(BackupDRClient.backup_path) + parse_backup_path = staticmethod(BackupDRClient.parse_backup_path) + backup_plan_path = staticmethod(BackupDRClient.backup_plan_path) + parse_backup_plan_path = staticmethod(BackupDRClient.parse_backup_plan_path) + backup_plan_association_path = staticmethod( + BackupDRClient.backup_plan_association_path + ) + parse_backup_plan_association_path = staticmethod( + BackupDRClient.parse_backup_plan_association_path + ) + backup_plan_revision_path = staticmethod(BackupDRClient.backup_plan_revision_path) + parse_backup_plan_revision_path = staticmethod( + BackupDRClient.parse_backup_plan_revision_path + ) + backup_vault_path = staticmethod(BackupDRClient.backup_vault_path) + parse_backup_vault_path = staticmethod(BackupDRClient.parse_backup_vault_path) + binding_matching_resource_path = staticmethod( + BackupDRClient.binding_matching_resource_path + ) + parse_binding_matching_resource_path = staticmethod( + BackupDRClient.parse_binding_matching_resource_path + ) + cluster_path = staticmethod(BackupDRClient.cluster_path) + parse_cluster_path = staticmethod(BackupDRClient.parse_cluster_path) + crypto_key_path = staticmethod(BackupDRClient.crypto_key_path) + parse_crypto_key_path = staticmethod(BackupDRClient.parse_crypto_key_path) + crypto_key_version_path = staticmethod(BackupDRClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod( + BackupDRClient.parse_crypto_key_version_path + ) + data_source_path = staticmethod(BackupDRClient.data_source_path) + parse_data_source_path = staticmethod(BackupDRClient.parse_data_source_path) + data_source_reference_path = staticmethod(BackupDRClient.data_source_reference_path) + parse_data_source_reference_path = staticmethod( + BackupDRClient.parse_data_source_reference_path + ) + instance_path = staticmethod(BackupDRClient.instance_path) + parse_instance_path = staticmethod(BackupDRClient.parse_instance_path) + management_server_path = staticmethod(BackupDRClient.management_server_path) + parse_management_server_path = staticmethod( + BackupDRClient.parse_management_server_path + ) + storage_pool_path = staticmethod(BackupDRClient.storage_pool_path) + parse_storage_pool_path = staticmethod(BackupDRClient.parse_storage_pool_path) + common_billing_account_path = staticmethod( + BackupDRClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + BackupDRClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(BackupDRClient.common_folder_path) + parse_common_folder_path = staticmethod(BackupDRClient.parse_common_folder_path) + common_organization_path = staticmethod(BackupDRClient.common_organization_path) + parse_common_organization_path = staticmethod( + BackupDRClient.parse_common_organization_path + ) + common_project_path = staticmethod(BackupDRClient.common_project_path) + parse_common_project_path = staticmethod(BackupDRClient.parse_common_project_path) + common_location_path = staticmethod(BackupDRClient.common_location_path) + parse_common_location_path = staticmethod(BackupDRClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDRAsyncClient: The constructed client. + """ + sa_info_func = ( + BackupDRClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(BackupDRAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDRAsyncClient: The constructed client. + """ + sa_file_func = ( + BackupDRClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(BackupDRAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return BackupDRClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> BackupDRTransport: + """Returns the transport used by the client instance. + + Returns: + BackupDRTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = BackupDRClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, BackupDRTransport, Callable[..., BackupDRTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the backup dr async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,BackupDRTransport,Callable[..., BackupDRTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the BackupDRTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = BackupDRClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.backupdr_v1beta.BackupDRAsyncClient`.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "credentialsType": None, + }, + ) + + async def list_management_servers( + self, + request: Optional[Union[backupdr.ListManagementServersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListManagementServersAsyncPager: + r"""Lists ManagementServers in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_management_servers(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListManagementServersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_management_servers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListManagementServersRequest, dict]]): + The request object. Request message for listing + management servers. + parent (:class:`str`): + Required. The project and location for which to retrieve + management servers information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + management servers for all locations, use "-" for the + '{location}' value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersAsyncPager: + Response message for listing + management servers. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.ListManagementServersRequest): + request = backupdr.ListManagementServersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_management_servers + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListManagementServersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_management_server( + self, + request: Optional[Union[backupdr.GetManagementServerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupdr.ManagementServer: + r"""Gets details of a single ManagementServer. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetManagementServerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_management_server(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetManagementServerRequest, dict]]): + The request object. Request message for getting a + management server instance. + name (:class:`str`): + Required. Name of the management server resource name, + in the format + 'projects/{project_id}/locations/{location}/managementServers/{resource_name}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.ManagementServer: + ManagementServer describes a single + BackupDR ManagementServer instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.GetManagementServerRequest): + request = backupdr.GetManagementServerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_management_server + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_management_server( + self, + request: Optional[Union[backupdr.CreateManagementServerRequest, dict]] = None, + *, + parent: Optional[str] = None, + management_server: Optional[backupdr.ManagementServer] = None, + management_server_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ManagementServer in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + ) + + # Make the request + operation = await client.create_management_server(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateManagementServerRequest, dict]]): + The request object. Request message for creating a + management server instance. + parent (:class:`str`): + Required. The management server project and location in + the format 'projects/{project_id}/locations/{location}'. + In Google Cloud Backup and DR locations map to Google + Cloud regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server (:class:`google.cloud.backupdr_v1beta.types.ManagementServer`): + Required. A [management server + resource][google.cloud.backupdr.v1.ManagementServer] + + This corresponds to the ``management_server`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server_id (:class:`str`): + Required. The name of the management + server to create. The name must be + unique for the specified project and + location. + + This corresponds to the ``management_server_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.ManagementServer` + ManagementServer describes a single BackupDR + ManagementServer instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, management_server, management_server_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.CreateManagementServerRequest): + request = backupdr.CreateManagementServerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if management_server is not None: + request.management_server = management_server + if management_server_id is not None: + request.management_server_id = management_server_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_management_server + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupdr.ManagementServer, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_management_server( + self, + request: Optional[Union[backupdr.DeleteManagementServerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single ManagementServer. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_delete_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteManagementServerRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_management_server(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest, dict]]): + The request object. Request message for deleting a + management server instance. + name (:class:`str`): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.DeleteManagementServerRequest): + request = backupdr.DeleteManagementServerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_management_server + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_backup_vault( + self, + request: Optional[Union[backupvault.CreateBackupVaultRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup_vault: Optional[backupvault.BackupVault] = None, + backup_vault_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new BackupVault in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) + + # Make the request + operation = await client.create_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateBackupVaultRequest, dict]]): + The request object. Message for creating a BackupVault. + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_vault (:class:`google.cloud.backupdr_v1beta.types.BackupVault`): + Required. The resource being created + This corresponds to the ``backup_vault`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_vault_id (:class:`str`): + Required. ID of the requesting object If auto-generating + ID server-side, remove this field and backup_vault_id + from the method_signature of Create RPC + + This corresponds to the ``backup_vault_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.BackupVault` + Message describing a BackupVault object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, backup_vault, backup_vault_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.CreateBackupVaultRequest): + request = backupvault.CreateBackupVaultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup_vault is not None: + request.backup_vault = backup_vault + if backup_vault_id is not None: + request.backup_vault_id = backup_vault_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_backup_vault + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupvault.BackupVault, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backup_vaults( + self, + request: Optional[Union[backupvault.ListBackupVaultsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupVaultsAsyncPager: + r"""Lists BackupVaults in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_vaults(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest, dict]]): + The request object. Request message for listing + backupvault stores. + parent (:class:`str`): + Required. The project and location for which to retrieve + backupvault stores information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + backupvault stores for all locations, use "-" for the + '{location}' value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsAsyncPager: + Response message for listing + BackupVaults. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.ListBackupVaultsRequest): + request = backupvault.ListBackupVaultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_backup_vaults + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupVaultsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fetch_usable_backup_vaults( + self, + request: Optional[ + Union[backupvault.FetchUsableBackupVaultsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchUsableBackupVaultsAsyncPager: + r"""FetchUsableBackupVaults lists usable BackupVaults in + a given project and location. Usable BackupVault are the + ones that user has backupdr.backupVaults.get permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_fetch_usable_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchUsableBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.fetch_usable_backup_vaults(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest, dict]]): + The request object. Request message for fetching usable + BackupVaults. + parent (:class:`str`): + Required. The project and location for which to retrieve + backupvault stores information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + backupvault stores for all locations, use "-" for the + '{location}' value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsAsyncPager: + Response message for fetching usable + BackupVaults. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.FetchUsableBackupVaultsRequest): + request = backupvault.FetchUsableBackupVaultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_usable_backup_vaults + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchUsableBackupVaultsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup_vault( + self, + request: Optional[Union[backupvault.GetBackupVaultRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.BackupVault: + r"""Gets details of a BackupVault. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupVaultRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_vault(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetBackupVaultRequest, dict]]): + The request object. Request message for getting a + BackupVault. + name (:class:`str`): + Required. Name of the backupvault store resource name, + in the format + 'projects/{project_id}/locations/{location}/backupVaults/{resource_name}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupVault: + Message describing a BackupVault + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.GetBackupVaultRequest): + request = backupvault.GetBackupVaultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_backup_vault + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_backup_vault( + self, + request: Optional[Union[backupvault.UpdateBackupVaultRequest, dict]] = None, + *, + backup_vault: Optional[backupvault.BackupVault] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the settings of a BackupVault. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_update_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupVaultRequest( + ) + + # Make the request + operation = await client.update_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.UpdateBackupVaultRequest, dict]]): + The request object. Request message for updating a + BackupVault. + backup_vault (:class:`google.cloud.backupdr_v1beta.types.BackupVault`): + Required. The resource being updated + This corresponds to the ``backup_vault`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the BackupVault resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.BackupVault` + Message describing a BackupVault object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup_vault, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.UpdateBackupVaultRequest): + request = backupvault.UpdateBackupVaultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup_vault is not None: + request.backup_vault = backup_vault + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_backup_vault + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("backup_vault.name", request.backup_vault.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupvault.BackupVault, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup_vault( + self, + request: Optional[Union[backupvault.DeleteBackupVaultRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a BackupVault. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_delete_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupVaultRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest, dict]]): + The request object. Message for deleting a BackupVault. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.DeleteBackupVaultRequest): + request = backupvault.DeleteBackupVaultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_backup_vault + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_data_sources( + self, + request: Optional[Union[backupvault.ListDataSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDataSourcesAsyncPager: + r"""Lists DataSources in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_data_sources(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListDataSourcesRequest, dict]]): + The request object. Request message for listing + DataSources. + parent (:class:`str`): + Required. The project and location for which to retrieve + data sources information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve data + sources for all locations, use "-" for the '{location}' + value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesAsyncPager: + Response message for listing + DataSources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.ListDataSourcesRequest): + request = backupvault.ListDataSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_data_sources + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_source( + self, + request: Optional[Union[backupvault.GetDataSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.DataSource: + r"""Gets details of a DataSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetDataSourceRequest, dict]]): + The request object. Request message for getting a + DataSource instance. + name (:class:`str`): + Required. Name of the data source resource name, in the + format + 'projects/{project_id}/locations/{location}/backupVaults/{resource_name}/dataSource/{resource_name}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.DataSource: + Message describing a DataSource + object. Datasource object used to + represent Datasource details for both + admin and basic view. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.GetDataSourceRequest): + request = backupvault.GetDataSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_data_source + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_data_source( + self, + request: Optional[Union[backupvault.UpdateDataSourceRequest, dict]] = None, + *, + data_source: Optional[backupvault.DataSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the settings of a DataSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_update_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateDataSourceRequest( + ) + + # Make the request + operation = await client.update_data_source(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.UpdateDataSourceRequest, dict]]): + The request object. Request message for updating a data + source instance. + data_source (:class:`google.cloud.backupdr_v1beta.types.DataSource`): + Required. The resource being updated + This corresponds to the ``data_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the DataSource resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.DataSource` Message describing a DataSource object. + Datasource object used to represent Datasource + details for both admin and basic view. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [data_source, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.UpdateDataSourceRequest): + request = backupvault.UpdateDataSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_source is not None: + request.data_source = data_source + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_data_source + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("data_source.name", request.data_source.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupvault.DataSource, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backups( + self, + request: Optional[Union[backupvault.ListBackupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupsAsyncPager: + r"""Lists Backups in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_backups(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListBackupsRequest, dict]]): + The request object. Request message for listing Backups. + parent (:class:`str`): + Required. The project and location for which to retrieve + backup information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve data + sources for all locations, use "-" for the '{location}' + value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsAsyncPager: + Response message for listing Backups. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.ListBackupsRequest): + request = backupvault.ListBackupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_backups + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fetch_backups_for_resource_type( + self, + request: Optional[ + Union[backupvault.FetchBackupsForResourceTypeRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + resource_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchBackupsForResourceTypeAsyncPager: + r"""Fetch Backups for a given resource type. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_fetch_backups_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backups_for_resource_type(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest, dict]]): + The request object. Request for the + FetchBackupsForResourceType method. + parent (:class:`str`): + Required. Datasources are the parent + resource for the backups. Format: + + projects/{project}/locations/{location}/backupVaults/{backupVaultId}/dataSources/{datasourceId} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource_type (:class:`str`): + Required. The type of the GCP + resource. Ex: + sqladmin.googleapis.com/Instance + + This corresponds to the ``resource_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypeAsyncPager: + Response for the + FetchBackupsForResourceType method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, resource_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.FetchBackupsForResourceTypeRequest): + request = backupvault.FetchBackupsForResourceTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource_type is not None: + request.resource_type = resource_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_backups_for_resource_type + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchBackupsForResourceTypeAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup( + self, + request: Optional[Union[backupvault.GetBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.Backup: + r"""Gets details of a Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetBackupRequest, dict]]): + The request object. Request message for getting a Backup. + name (:class:`str`): + Required. Name of the data source resource name, in the + format + 'projects/{project_id}/locations/{location}/backupVaults/{backupVault}/dataSources/{datasource}/backups/{backup}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.Backup: + Message describing a Backup object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.GetBackupRequest): + request = backupvault.GetBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_backup( + self, + request: Optional[Union[backupvault.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[backupvault.Backup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the settings of a Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_update_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupRequest( + ) + + # Make the request + operation = await client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.UpdateBackupRequest, dict]]): + The request object. Request message for updating a + Backup. + backup (:class:`google.cloud.backupdr_v1beta.types.Backup`): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.Backup` + Message describing a Backup object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.UpdateBackupRequest): + request = backupvault.UpdateBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("backup.name", request.backup.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupvault.Backup, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_backup( + self, + request: Optional[Union[backupvault.DeleteBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_delete_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteBackupRequest, dict]]): + The request object. Message for deleting a Backup. + name (:class:`str`): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.Backup` + Message describing a Backup object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.DeleteBackupRequest): + request = backupvault.DeleteBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupvault.Backup, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restore_backup( + self, + request: Optional[Union[backupvault.RestoreBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Restore from a Backup + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_restore_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + compute_instance_target_environment = backupdr_v1beta.ComputeInstanceTargetEnvironment() + compute_instance_target_environment.project = "project_value" + compute_instance_target_environment.zone = "zone_value" + + request = backupdr_v1beta.RestoreBackupRequest( + compute_instance_target_environment=compute_instance_target_environment, + name="name_value", + ) + + # Make the request + operation = await client.restore_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.RestoreBackupRequest, dict]]): + The request object. Request message for restoring from a + Backup. + name (:class:`str`): + Required. The resource name of the Backup instance, in + the format + 'projects/*/locations/*/backupVaults/*/dataSources/*/backups/'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.RestoreBackupResponse` + Response message for restoring from a Backup. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.RestoreBackupRequest): + request = backupvault.RestoreBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.restore_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupvault.RestoreBackupResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_backup_plan( + self, + request: Optional[Union[backupplan.CreateBackupPlanRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup_plan: Optional[backupplan.BackupPlan] = None, + backup_plan_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a BackupPlan + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.CreateBackupPlanRequest( + parent="parent_value", + backup_plan_id="backup_plan_id_value", + backup_plan=backup_plan, + ) + + # Make the request + operation = await client.create_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateBackupPlanRequest, dict]]): + The request object. The request message for creating a ``BackupPlan``. + parent (:class:`str`): + Required. The ``BackupPlan`` project and location in the + format ``projects/{project}/locations/{location}``. In + Google Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan (:class:`google.cloud.backupdr_v1beta.types.BackupPlan`): + Required. The ``BackupPlan`` resource object to create. + This corresponds to the ``backup_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan_id (:class:`str`): + Required. The name of the ``BackupPlan`` to create. The + name must be unique for the specified project and + location.The name must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, or + hyphens. Pattern, /[a-z][a-z0-9-]{,62}/. + + This corresponds to the ``backup_plan_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlan` A BackupPlan specifies some common fields, such as description as well + as one or more BackupRule messages. Each BackupRule + has a retention policy and defines a schedule by + which the system is to perform backup workloads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, backup_plan, backup_plan_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.CreateBackupPlanRequest): + request = backupplan.CreateBackupPlanRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup_plan is not None: + request.backup_plan = backup_plan + if backup_plan_id is not None: + request.backup_plan_id = backup_plan_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_backup_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupplan.BackupPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_backup_plan( + self, + request: Optional[Union[backupplan.UpdateBackupPlanRequest, dict]] = None, + *, + backup_plan: Optional[backupplan.BackupPlan] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a BackupPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_update_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.UpdateBackupPlanRequest( + backup_plan=backup_plan, + ) + + # Make the request + operation = await client.update_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.UpdateBackupPlanRequest, dict]]): + The request object. Request message for updating a backup + plan. + backup_plan (:class:`google.cloud.backupdr_v1beta.types.BackupPlan`): + Required. The resource being updated + This corresponds to the ``backup_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + BackupPlan resource by the update. The fields specified + in the update_mask are relative to the resource, not the + full request. A field will be overwritten if it is in + the mask. If the user does not provide a mask then the + request will fail. Currently, these fields are supported + in update: description, schedules, retention period, + adding and removing Backup Rules. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlan` A BackupPlan specifies some common fields, such as description as well + as one or more BackupRule messages. Each BackupRule + has a retention policy and defines a schedule by + which the system is to perform backup workloads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup_plan, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.UpdateBackupPlanRequest): + request = backupplan.UpdateBackupPlanRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup_plan is not None: + request.backup_plan = backup_plan + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_backup_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("backup_plan.name", request.backup_plan.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupplan.BackupPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_backup_plan( + self, + request: Optional[Union[backupplan.GetBackupPlanRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlan: + r"""Gets details of a single BackupPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_plan(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetBackupPlanRequest, dict]]): + The request object. The request message for getting a ``BackupPlan``. + name (:class:`str`): + Required. The resource name of the ``BackupPlan`` to + retrieve. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupPlan: + A BackupPlan specifies some common fields, such as description as well + as one or more BackupRule messages. Each BackupRule + has a retention policy and defines a schedule by + which the system is to perform backup workloads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.GetBackupPlanRequest): + request = backupplan.GetBackupPlanRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_backup_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_backup_plans( + self, + request: Optional[Union[backupplan.ListBackupPlansRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupPlansAsyncPager: + r"""Lists BackupPlans in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_backup_plans(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plans(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListBackupPlansRequest, dict]]): + The request object. The request message for getting a list ``BackupPlan``. + parent (:class:`str`): + Required. The project and location for which to retrieve + ``BackupPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for e.g. **us-central1**. To retrieve backup + plans for all locations, use "-" for the ``{location}`` + value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansAsyncPager: + The response message for getting a list of BackupPlan. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.ListBackupPlansRequest): + request = backupplan.ListBackupPlansRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_backup_plans + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupPlansAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_backup_plan( + self, + request: Optional[Union[backupplan.DeleteBackupPlanRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single BackupPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_delete_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest, dict]]): + The request object. The request message for deleting a ``BackupPlan``. + name (:class:`str`): + Required. The resource name of the ``BackupPlan`` to + delete. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.DeleteBackupPlanRequest): + request = backupplan.DeleteBackupPlanRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_backup_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_backup_plan_revision( + self, + request: Optional[Union[backupplan.GetBackupPlanRevisionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlanRevision: + r"""Gets details of a single BackupPlanRevision. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_backup_plan_revision(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_plan_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest, dict]]): + The request object. The request message for getting a + ``BackupPlanRevision``. + name (:class:`str`): + Required. The resource name of the + ``BackupPlanRevision`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupPlanRevision: + BackupPlanRevision represents a snapshot of a BackupPlan at a point in + time. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.GetBackupPlanRevisionRequest): + request = backupplan.GetBackupPlanRevisionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_backup_plan_revision + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_backup_plan_revisions( + self, + request: Optional[ + Union[backupplan.ListBackupPlanRevisionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupPlanRevisionsAsyncPager: + r"""Lists BackupPlanRevisions in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_backup_plan_revisions(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest, dict]]): + The request object. The request message for getting a list of + ``BackupPlanRevision``. + parent (:class:`str`): + Required. The project and location for which to retrieve + ``BackupPlanRevisions`` information. Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}``. + In Google Cloud Backup and DR, locations map to Google + Cloud regions, for e.g. **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsAsyncPager: + The response message for getting a list of + BackupPlanRevision. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.ListBackupPlanRevisionsRequest): + request = backupplan.ListBackupPlanRevisionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_backup_plan_revisions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupPlanRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.CreateBackupPlanAssociationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + backup_plan_association: Optional[ + backupplanassociation.BackupPlanAssociation + ] = None, + backup_plan_association_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a BackupPlanAssociation + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = await client.create_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateBackupPlanAssociationRequest, dict]]): + The request object. Request message for creating a backup + plan. + parent (:class:`str`): + Required. The backup plan association project and + location in the format + ``projects/{project_id}/locations/{location}``. In + Backup and DR locations map to Google Cloud regions, for + example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan_association (:class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation`): + Required. The resource being created + This corresponds to the ``backup_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan_association_id (:class:`str`): + Required. The name of the backup plan + association to create. The name must be + unique for the specified project and + location. + + This corresponds to the ``backup_plan_association_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation` A BackupPlanAssociation represents a single BackupPlanAssociation which + contains details like workload, backup plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, backup_plan_association, backup_plan_association_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.CreateBackupPlanAssociationRequest + ): + request = backupplanassociation.CreateBackupPlanAssociationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup_plan_association is not None: + request.backup_plan_association = backup_plan_association + if backup_plan_association_id is not None: + request.backup_plan_association_id = backup_plan_association_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupplanassociation.BackupPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.UpdateBackupPlanAssociationRequest, dict] + ] = None, + *, + backup_plan_association: Optional[ + backupplanassociation.BackupPlanAssociation + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a BackupPlanAssociation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_update_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.UpdateBackupPlanAssociationRequest( + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = await client.update_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.UpdateBackupPlanAssociationRequest, dict]]): + The request object. Request message for updating a backup + plan association. + backup_plan_association (:class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation`): + Required. The resource being updated + This corresponds to the ``backup_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + BackupPlanAssociation resource by the update. The fields + specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. Currently + backup_plan_association.backup_plan is the only + supported field. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation` A BackupPlanAssociation represents a single BackupPlanAssociation which + contains details like workload, backup plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup_plan_association, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.UpdateBackupPlanAssociationRequest + ): + request = backupplanassociation.UpdateBackupPlanAssociationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup_plan_association is not None: + request.backup_plan_association = backup_plan_association + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "backup_plan_association.name", + request.backup_plan_association.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupplanassociation.BackupPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.GetBackupPlanAssociationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.BackupPlanAssociation: + r"""Gets details of a single BackupPlanAssociation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_plan_association(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest, dict]]): + The request object. Request message for getting a + BackupPlanAssociation resource. + name (:class:`str`): + Required. Name of the backup plan association resource, + in the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupPlanAssociation: + A BackupPlanAssociation represents a + single BackupPlanAssociation which + contains details like workload, backup + plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.GetBackupPlanAssociationRequest + ): + request = backupplanassociation.GetBackupPlanAssociationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_backup_plan_associations( + self, + request: Optional[ + Union[backupplanassociation.ListBackupPlanAssociationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupPlanAssociationsAsyncPager: + r"""Lists BackupPlanAssociations in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_backup_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_associations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest, dict]]): + The request object. Request message for List + BackupPlanAssociation + parent (:class:`str`): + Required. The project and location for which to retrieve + backup Plan Associations information, in the format + ``projects/{project_id}/locations/{location}``. In + Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. To retrieve backup plan + associations for all locations, use "-" for the + ``{location}`` value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsAsyncPager: + Response message for List + BackupPlanAssociation + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.ListBackupPlanAssociationsRequest + ): + request = backupplanassociation.ListBackupPlanAssociationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_backup_plan_associations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupPlanAssociationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fetch_backup_plan_associations_for_resource_type( + self, + request: Optional[ + Union[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + resource_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager: + r"""List BackupPlanAssociations for a given resource + type. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_fetch_backup_plan_associations_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backup_plan_associations_for_resource_type(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest, dict]]): + The request object. Request for the + FetchBackupPlanAssociationsForResourceType + method. + parent (:class:`str`): + Required. The parent resource name. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource_type (:class:`str`): + Required. The type of the Google + Cloud resource. Ex: + sql.googleapis.com/Instance + + This corresponds to the ``resource_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager: + Response for the + FetchBackupPlanAssociationsForResourceType + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, resource_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + ): + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource_type is not None: + request.resource_type = resource_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_backup_plan_associations_for_resource_type + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.DeleteBackupPlanAssociationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single BackupPlanAssociation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_delete_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest, dict]]): + The request object. Request message for deleting a backup + plan association. + name (:class:`str`): + Required. Name of the backup plan association resource, + in the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.DeleteBackupPlanAssociationRequest + ): + request = backupplanassociation.DeleteBackupPlanAssociationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def trigger_backup( + self, + request: Optional[ + Union[backupplanassociation.TriggerBackupRequest, dict] + ] = None, + *, + name: Optional[str] = None, + rule_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Triggers a new Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_trigger_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerBackupRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.TriggerBackupRequest, dict]]): + The request object. Request message for triggering a + backup. + name (:class:`str`): + Required. Name of the backup plan association resource, + in the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rule_id (:class:`str`): + Optional. backup rule_id for which a backup needs to be + triggered. If not specified, on-demand backup with + custom retention will be triggered. + + This corresponds to the ``rule_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation` A BackupPlanAssociation represents a single BackupPlanAssociation which + contains details like workload, backup plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, rule_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplanassociation.TriggerBackupRequest): + request = backupplanassociation.TriggerBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if rule_id is not None: + request.rule_id = rule_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.trigger_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupplanassociation.BackupPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_data_source_reference( + self, + request: Optional[ + Union[datasourcereference.GetDataSourceReferenceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasourcereference.DataSourceReference: + r"""Gets details of a single DataSourceReference. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_data_source_reference(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceReferenceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_source_reference(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest, dict]]): + The request object. Request for the + GetDataSourceReference method. + name (:class:`str`): + Required. The name of the DataSourceReference to + retrieve. Format: + projects/{project}/locations/{location}/dataSourceReferences/{data_source_reference} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.DataSourceReference: + DataSourceReference is a reference to + a DataSource resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasourcereference.GetDataSourceReferenceRequest): + request = datasourcereference.GetDataSourceReferenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_data_source_reference + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_data_source_references( + self, + request: Optional[ + Union[datasourcereference.ListDataSourceReferencesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDataSourceReferencesAsyncPager: + r"""Lists DataSourceReferences for a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_data_source_references(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourceReferencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_source_references(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest, dict]]): + The request object. Request for the + ListDataSourceReferences method. + parent (:class:`str`): + Required. The parent resource name. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesAsyncPager: + Response for the + ListDataSourceReferences method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasourcereference.ListDataSourceReferencesRequest): + request = datasourcereference.ListDataSourceReferencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_data_source_references + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataSourceReferencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fetch_data_source_references_for_resource_type( + self, + request: Optional[ + Union[ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + resource_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchDataSourceReferencesForResourceTypeAsyncPager: + r"""Fetch DataSourceReferences for a given project, + location and resource type. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_fetch_data_source_references_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_data_source_references_for_resource_type(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest, dict]]): + The request object. Request for the + FetchDataSourceReferencesForResourceType + method. + parent (:class:`str`): + Required. The parent resource name. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource_type (:class:`str`): + Required. The type of the Google + Cloud resource. Ex: + sql.googleapis.com/Instance + + This corresponds to the ``resource_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypeAsyncPager: + Response for the + FetchDataSourceReferencesForResourceType + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, resource_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, datasourcereference.FetchDataSourceReferencesForResourceTypeRequest + ): + request = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource_type is not None: + request.resource_type = resource_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_data_source_references_for_resource_type + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchDataSourceReferencesForResourceTypeAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def initialize_service( + self, + request: Optional[Union[backupdr.InitializeServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Initializes the service related config for a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_initialize_service(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + cloud_sql_instance_initialization_config = backupdr_v1beta.CloudSqlInstanceInitializationConfig() + cloud_sql_instance_initialization_config.edition = "ENTERPRISE_PLUS" + + request = backupdr_v1beta.InitializeServiceRequest( + cloud_sql_instance_initialization_config=cloud_sql_instance_initialization_config, + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = await client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.InitializeServiceRequest, dict]]): + The request object. Request message for initializing the + service. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.InitializeServiceResponse` + Response message for initializing the service. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.InitializeServiceRequest): + request = backupdr.InitializeServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.initialize_service + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupdr.InitializeServiceResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.CreateAutoProtectionPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + auto_protection_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new AutoProtectionPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1beta.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyRequest, dict]]): + The request object. Request message for creating an + AutoProtectionPolicy. + parent (:class:`str`): + Required. The parent resource where + this policy will be created. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy (:class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicy`): + Required. The AutoProtectionPolicy + resource to create. + + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_id (:class:`str`): + Required. The ID to use for the + policy. This will become the final + component of the policy's resource name. + + This corresponds to the ``auto_protection_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, auto_protection_policy, auto_protection_policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.CreateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if auto_protection_policy_id is not None: + request.auto_protection_policy_id = auto_protection_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_auto_protection_policies( + self, + request: Optional[ + Union[autoprotectionpolicy.ListAutoProtectionPoliciesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAutoProtectionPoliciesAsyncPager: + r"""Lists AutoProtectionPolicies for a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest, dict]]): + The request object. Request message for + ListAutoProtectionPolicies. + parent (:class:`str`): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesAsyncPager: + Response message for + ListAutoProtectionPolicies. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.ListAutoProtectionPoliciesRequest + ): + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_auto_protection_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAutoProtectionPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.GetAutoProtectionPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicy.AutoProtectionPolicy: + r"""Gets details of a single AutoProtectionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest, dict]]): + The request object. Request message for getting an + AutoProtectionPolicy. + name (:class:`str`): + Required. The name of the policy to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.AutoProtectionPolicy: + An AutoprotectionPolicy is a policy + resource designed to automate backup + management, moving from manual + per-resource protection to a bulk + approach. The policy dynamically + discovers and applies a specified backup + plan to all eligible resources that + match its defined scope and criteria. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autoprotectionpolicy.GetAutoProtectionPolicyRequest): + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, dict] + ] = None, + *, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single + AutoProtectionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1beta.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.UpdateAutoProtectionPolicyRequest, dict]]): + The request object. Request message for updating an + AutoProtectionPolicy. + auto_protection_policy (:class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicy`): + Required. The policy to update. + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the AutoProtectionPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [auto_protection_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.UpdateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("auto_protection_policy.name", request.auto_protection_policy.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single AutoProtectionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest, dict]]): + The request object. Request message for deleting an + AutoProtectionPolicy. + name (:class:`str`): + Required. The name of the policy to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.DeleteAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy_binding: Optional[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding + ] = None, + auto_protection_policy_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new AutoProtectionPolicyBinding in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1beta.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1beta.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = await client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyBindingRequest, dict]]): + The request object. Request message for creating an + AutoProtectionPolicyBinding. + parent (:class:`str`): + Required. The parent resource where this binding will be + created. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding (:class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding`): + Required. The + AutoProtectionPolicyBinding resource to + create. + + This corresponds to the ``auto_protection_policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding_id (:class:`str`): + Required. The ID to use for the + binding. This will become the final + component of the binding's resource + name. + + This corresponds to the ``auto_protection_policy_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding` An AutoprotectionPolicyBinding (APPA) acts as the bridge between an + AutoprotectionPolicy and the scope (Project, Folder, + or Organization) where the policy should be applied. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + auto_protection_policy_binding, + auto_protection_policy_binding_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + ): + request = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy_binding is not None: + request.auto_protection_policy_binding = auto_protection_policy_binding + if auto_protection_policy_binding_id is not None: + request.auto_protection_policy_binding_id = ( + auto_protection_policy_binding_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, dict + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + r"""Returns the auto protection policy binding read from + the CCFE tables. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest, dict]]): + The request object. Request message for getting an + AutoProtectionPolicyBinding. + name (:class:`str`): + Required. The name of the binding to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding: + An AutoprotectionPolicyBinding (APPA) + acts as the bridge between an + AutoprotectionPolicy and the scope + (Project, Folder, or Organization) where + the policy should be applied. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest + ): + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_auto_protection_policy_bindings( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAutoProtectionPolicyBindingsAsyncPager: + r"""Returns the auto protection policy bindings read from + the CCFE tables. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest, dict]]): + The request object. Request message for + ListAutoProtectionPolicyBindings. + parent (:class:`str`): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsAsyncPager: + Response message for + ListAutoProtectionPolicyBindings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest + ): + request = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_auto_protection_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAutoProtectionPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_applied_auto_protection_policies( + self, + request: Optional[ + Union[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAppliedAutoProtectionPoliciesAsyncPager: + r"""Lists AppliedAutoProtectionPolicies in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest, dict]]): + The request object. Request message for listing + AppliedAutoProtectionPolicies. + parent (:class:`str`): + Required. The project and location + for which to retrieve the list of + applied policies. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesAsyncPager: + Response message for + ListAppliedAutoProtectionPolicies. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + ): + request = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_applied_auto_protection_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAppliedAutoProtectionPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def initiate_delete_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = await client.initiate_delete_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest, dict]]): + The request object. Request message for initiating delete + of an AutoProtectionPolicyBinding. + name (:class:`str`): + Required. The name of the binding to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding` An AutoprotectionPolicyBinding (APPA) acts as the bridge between an + AutoprotectionPolicy and the scope (Project, Folder, + or Organization) where the policy should be applied. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + ): + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.initiate_delete_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_binding_matching_resource( + self, + request: Optional[ + Union[bindingmatchingresource.GetBindingMatchingResourceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bindingmatchingresource.BindingMatchingResource: + r"""Gets details of a single Binding Matching Resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_get_binding_matching_resource(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBindingMatchingResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_binding_matching_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest, dict]]): + The request object. Request message for getting a + BindingMatchingResource. + name (:class:`str`): + Required. The name of the matching resource to retrieve. + Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BindingMatchingResource: + BindingMatchingResource contains the + details of a resource that matches the + criteria of a binding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bindingmatchingresource.GetBindingMatchingResourceRequest + ): + request = bindingmatchingresource.GetBindingMatchingResourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_binding_matching_resource + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_binding_matching_resources( + self, + request: Optional[ + Union[bindingmatchingresource.ListBindingMatchingResourcesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBindingMatchingResourcesAsyncPager: + r"""Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest, dict]]): + The request object. Request message for List + BindingMatchingResources. + parent (:class:`str`): + Required. The project, location, auto protection policy + and binding for which to retrieve + ``BindingMatchingResources`` information. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}``. + In Google Cloud Backup and DR, locations map to Google + Cloud regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesAsyncPager: + The response message for getting a list of + BindingMatchingResources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bindingmatchingresource.ListBindingMatchingResourcesRequest + ): + request = bindingmatchingresource.ListBindingMatchingResourcesRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_binding_matching_resources + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBindingMatchingResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "BackupDRAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("BackupDRAsyncClient",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/client.py new file mode 100644 index 000000000000..057a8812394e --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/client.py @@ -0,0 +1,8212 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.backupdr_v1beta import gapic_version as package_version +from google.cloud.backupdr_v1beta._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.backupdr_v1beta.services.backup_dr import pagers +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + backupvault_alloydb, + backupvault_ba, + backupvault_cloudsql, + backupvault_disk, + backupvault_gce, + bindingmatchingresource, + datasourcereference, +) + +from .transports.base import DEFAULT_CLIENT_INFO, BackupDRTransport +from .transports.grpc import BackupDRGrpcTransport +from .transports.grpc_asyncio import BackupDRGrpcAsyncIOTransport +from .transports.rest import BackupDRRestTransport + + +class BackupDRClientMeta(type): + """Metaclass for the BackupDR client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[BackupDRTransport]] + _transport_registry["grpc"] = BackupDRGrpcTransport + _transport_registry["grpc_asyncio"] = BackupDRGrpcAsyncIOTransport + _transport_registry["rest"] = BackupDRRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[BackupDRTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class BackupDRClient(metaclass=BackupDRClientMeta): + """The BackupDR Service""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "backupdr.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "backupdr.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDRClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDRClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> BackupDRTransport: + """Returns the transport used by the client instance. + + Returns: + BackupDRTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def applied_auto_protection_policy_path( + project: str, + location: str, + applied_auto_protection_policy: str, + ) -> str: + """Returns a fully-qualified applied_auto_protection_policy string.""" + return "projects/{project}/locations/{location}/appliedAutoProtectionPolicies/{applied_auto_protection_policy}".format( + project=project, + location=location, + applied_auto_protection_policy=applied_auto_protection_policy, + ) + + @staticmethod + def parse_applied_auto_protection_policy_path(path: str) -> Dict[str, str]: + """Parses a applied_auto_protection_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/appliedAutoProtectionPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def auto_protection_policy_path( + project: str, + location: str, + auto_protection_policy: str, + ) -> str: + """Returns a fully-qualified auto_protection_policy string.""" + return "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + ) + + @staticmethod + def parse_auto_protection_policy_path(path: str) -> Dict[str, str]: + """Parses a auto_protection_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/autoProtectionPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def auto_protection_policy_binding_path( + project: str, + location: str, + auto_protection_policy: str, + binding: str, + ) -> str: + """Returns a fully-qualified auto_protection_policy_binding string.""" + return "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + ) + + @staticmethod + def parse_auto_protection_policy_binding_path(path: str) -> Dict[str, str]: + """Parses a auto_protection_policy_binding path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/autoProtectionPolicies/(?P.+?)/bindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def backup_path( + project: str, + location: str, + backupvault: str, + datasource: str, + backup: str, + ) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource}/backups/{backup}".format( + project=project, + location=location, + backupvault=backupvault, + datasource=datasource, + backup=backup, + ) + + @staticmethod + def parse_backup_path(path: str) -> Dict[str, str]: + """Parses a backup path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupVaults/(?P.+?)/dataSources/(?P.+?)/backups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def backup_plan_path( + project: str, + location: str, + backup_plan: str, + ) -> str: + """Returns a fully-qualified backup_plan string.""" + return ( + "projects/{project}/locations/{location}/backupPlans/{backup_plan}".format( + project=project, + location=location, + backup_plan=backup_plan, + ) + ) + + @staticmethod + def parse_backup_plan_path(path: str) -> Dict[str, str]: + """Parses a backup_plan path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupPlans/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def backup_plan_association_path( + project: str, + location: str, + backup_plan_association: str, + ) -> str: + """Returns a fully-qualified backup_plan_association string.""" + return "projects/{project}/locations/{location}/backupPlanAssociations/{backup_plan_association}".format( + project=project, + location=location, + backup_plan_association=backup_plan_association, + ) + + @staticmethod + def parse_backup_plan_association_path(path: str) -> Dict[str, str]: + """Parses a backup_plan_association path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupPlanAssociations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def backup_plan_revision_path( + project: str, + location: str, + backup_plan: str, + revision: str, + ) -> str: + """Returns a fully-qualified backup_plan_revision string.""" + return "projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision}".format( + project=project, + location=location, + backup_plan=backup_plan, + revision=revision, + ) + + @staticmethod + def parse_backup_plan_revision_path(path: str) -> Dict[str, str]: + """Parses a backup_plan_revision path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupPlans/(?P.+?)/revisions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def backup_vault_path( + project: str, + location: str, + backupvault: str, + ) -> str: + """Returns a fully-qualified backup_vault string.""" + return ( + "projects/{project}/locations/{location}/backupVaults/{backupvault}".format( + project=project, + location=location, + backupvault=backupvault, + ) + ) + + @staticmethod + def parse_backup_vault_path(path: str) -> Dict[str, str]: + """Parses a backup_vault path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupVaults/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def binding_matching_resource_path( + project: str, + location: str, + auto_protection_policy: str, + binding: str, + matching_resource: str, + ) -> str: + """Returns a fully-qualified binding_matching_resource string.""" + return "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + matching_resource=matching_resource, + ) + + @staticmethod + def parse_binding_matching_resource_path(path: str) -> Dict[str, str]: + """Parses a binding_matching_resource path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/autoProtectionPolicies/(?P.+?)/bindings/(?P.+?)/matchingResources/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def cluster_path( + project: str, + location: str, + cluster: str, + ) -> str: + """Returns a fully-qualified cluster string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}".format( + project=project, + location=location, + cluster=cluster, + ) + + @staticmethod + def parse_cluster_path(path: str) -> Dict[str, str]: + """Parses a cluster path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_path( + project: str, + location: str, + ring: str, + key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{ring}/cryptoKeys/{key}".format( + project=project, + location=location, + ring=ring, + key=key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + crypto_key_version: str, + ) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str, str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def data_source_path( + project: str, + location: str, + backupvault: str, + datasource: str, + ) -> str: + """Returns a fully-qualified data_source string.""" + return "projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource}".format( + project=project, + location=location, + backupvault=backupvault, + datasource=datasource, + ) + + @staticmethod + def parse_data_source_path(path: str) -> Dict[str, str]: + """Parses a data_source path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupVaults/(?P.+?)/dataSources/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def data_source_reference_path( + project: str, + location: str, + data_source_reference: str, + ) -> str: + """Returns a fully-qualified data_source_reference string.""" + return "projects/{project}/locations/{location}/dataSourceReferences/{data_source_reference}".format( + project=project, + location=location, + data_source_reference=data_source_reference, + ) + + @staticmethod + def parse_data_source_reference_path(path: str) -> Dict[str, str]: + """Parses a data_source_reference path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataSourceReferences/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def instance_path( + project: str, + instance: str, + ) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/instances/{instance}".format( + project=project, + instance=instance, + ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str, str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/instances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def management_server_path( + project: str, + location: str, + managementserver: str, + ) -> str: + """Returns a fully-qualified management_server string.""" + return "projects/{project}/locations/{location}/managementServers/{managementserver}".format( + project=project, + location=location, + managementserver=managementserver, + ) + + @staticmethod + def parse_management_server_path(path: str) -> Dict[str, str]: + """Parses a management_server path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/managementServers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def storage_pool_path( + project: str, + zone: str, + storage_pool: str, + ) -> str: + """Returns a fully-qualified storage_pool string.""" + return "projects/{project}/zones/{zone}/storagePools/{storage_pool}".format( + project=project, + zone=zone, + storage_pool=storage_pool, + ) + + @staticmethod + def parse_storage_pool_path(path: str) -> Dict[str, str]: + """Parses a storage_pool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/zones/(?P.+?)/storagePools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, BackupDRTransport, Callable[..., BackupDRTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the backup dr client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,BackupDRTransport,Callable[..., BackupDRTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the BackupDRTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = BackupDRClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=BackupDRClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, BackupDRTransport) + if transport_provided: + # transport is a BackupDRTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(BackupDRTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=BackupDRClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=BackupDRClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=BackupDRClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[BackupDRTransport], Callable[..., BackupDRTransport] + ] = ( + BackupDRClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., BackupDRTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.backupdr_v1beta.BackupDRClient`.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "credentialsType": None, + }, + ) + + def list_management_servers( + self, + request: Optional[Union[backupdr.ListManagementServersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListManagementServersPager: + r"""Lists ManagementServers in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_management_servers(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListManagementServersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_management_servers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListManagementServersRequest, dict]): + The request object. Request message for listing + management servers. + parent (str): + Required. The project and location for which to retrieve + management servers information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + management servers for all locations, use "-" for the + '{location}' value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersPager: + Response message for listing + management servers. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.ListManagementServersRequest): + request = backupdr.ListManagementServersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_management_servers] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListManagementServersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_management_server( + self, + request: Optional[Union[backupdr.GetManagementServerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupdr.ManagementServer: + r"""Gets details of a single ManagementServer. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetManagementServerRequest( + name="name_value", + ) + + # Make the request + response = client.get_management_server(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetManagementServerRequest, dict]): + The request object. Request message for getting a + management server instance. + name (str): + Required. Name of the management server resource name, + in the format + 'projects/{project_id}/locations/{location}/managementServers/{resource_name}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.ManagementServer: + ManagementServer describes a single + BackupDR ManagementServer instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.GetManagementServerRequest): + request = backupdr.GetManagementServerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_management_server] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_management_server( + self, + request: Optional[Union[backupdr.CreateManagementServerRequest, dict]] = None, + *, + parent: Optional[str] = None, + management_server: Optional[backupdr.ManagementServer] = None, + management_server_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ManagementServer in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + ) + + # Make the request + operation = client.create_management_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateManagementServerRequest, dict]): + The request object. Request message for creating a + management server instance. + parent (str): + Required. The management server project and location in + the format 'projects/{project_id}/locations/{location}'. + In Google Cloud Backup and DR locations map to Google + Cloud regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server (google.cloud.backupdr_v1beta.types.ManagementServer): + Required. A [management server + resource][google.cloud.backupdr.v1.ManagementServer] + + This corresponds to the ``management_server`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server_id (str): + Required. The name of the management + server to create. The name must be + unique for the specified project and + location. + + This corresponds to the ``management_server_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.ManagementServer` + ManagementServer describes a single BackupDR + ManagementServer instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, management_server, management_server_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.CreateManagementServerRequest): + request = backupdr.CreateManagementServerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if management_server is not None: + request.management_server = management_server + if management_server_id is not None: + request.management_server_id = management_server_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_management_server] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupdr.ManagementServer, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_management_server( + self, + request: Optional[Union[backupdr.DeleteManagementServerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single ManagementServer. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_delete_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteManagementServerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_management_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest, dict]): + The request object. Request message for deleting a + management server instance. + name (str): + Required. Name of the resource + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.DeleteManagementServerRequest): + request = backupdr.DeleteManagementServerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_management_server] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_backup_vault( + self, + request: Optional[Union[backupvault.CreateBackupVaultRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup_vault: Optional[backupvault.BackupVault] = None, + backup_vault_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new BackupVault in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) + + # Make the request + operation = client.create_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateBackupVaultRequest, dict]): + The request object. Message for creating a BackupVault. + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_vault (google.cloud.backupdr_v1beta.types.BackupVault): + Required. The resource being created + This corresponds to the ``backup_vault`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_vault_id (str): + Required. ID of the requesting object If auto-generating + ID server-side, remove this field and backup_vault_id + from the method_signature of Create RPC + + This corresponds to the ``backup_vault_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.BackupVault` + Message describing a BackupVault object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, backup_vault, backup_vault_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.CreateBackupVaultRequest): + request = backupvault.CreateBackupVaultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup_vault is not None: + request.backup_vault = backup_vault + if backup_vault_id is not None: + request.backup_vault_id = backup_vault_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_backup_vault] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupvault.BackupVault, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backup_vaults( + self, + request: Optional[Union[backupvault.ListBackupVaultsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupVaultsPager: + r"""Lists BackupVaults in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_vaults(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest, dict]): + The request object. Request message for listing + backupvault stores. + parent (str): + Required. The project and location for which to retrieve + backupvault stores information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + backupvault stores for all locations, use "-" for the + '{location}' value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsPager: + Response message for listing + BackupVaults. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.ListBackupVaultsRequest): + request = backupvault.ListBackupVaultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_backup_vaults] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBackupVaultsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def fetch_usable_backup_vaults( + self, + request: Optional[ + Union[backupvault.FetchUsableBackupVaultsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchUsableBackupVaultsPager: + r"""FetchUsableBackupVaults lists usable BackupVaults in + a given project and location. Usable BackupVault are the + ones that user has backupdr.backupVaults.get permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_fetch_usable_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchUsableBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.fetch_usable_backup_vaults(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest, dict]): + The request object. Request message for fetching usable + BackupVaults. + parent (str): + Required. The project and location for which to retrieve + backupvault stores information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + backupvault stores for all locations, use "-" for the + '{location}' value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsPager: + Response message for fetching usable + BackupVaults. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.FetchUsableBackupVaultsRequest): + request = backupvault.FetchUsableBackupVaultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_usable_backup_vaults + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchUsableBackupVaultsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_backup_vault( + self, + request: Optional[Union[backupvault.GetBackupVaultRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.BackupVault: + r"""Gets details of a BackupVault. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupVaultRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_vault(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetBackupVaultRequest, dict]): + The request object. Request message for getting a + BackupVault. + name (str): + Required. Name of the backupvault store resource name, + in the format + 'projects/{project_id}/locations/{location}/backupVaults/{resource_name}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupVault: + Message describing a BackupVault + object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.GetBackupVaultRequest): + request = backupvault.GetBackupVaultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_backup_vault] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_backup_vault( + self, + request: Optional[Union[backupvault.UpdateBackupVaultRequest, dict]] = None, + *, + backup_vault: Optional[backupvault.BackupVault] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the settings of a BackupVault. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_update_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupVaultRequest( + ) + + # Make the request + operation = client.update_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.UpdateBackupVaultRequest, dict]): + The request object. Request message for updating a + BackupVault. + backup_vault (google.cloud.backupdr_v1beta.types.BackupVault): + Required. The resource being updated + This corresponds to the ``backup_vault`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the BackupVault resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.BackupVault` + Message describing a BackupVault object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup_vault, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.UpdateBackupVaultRequest): + request = backupvault.UpdateBackupVaultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup_vault is not None: + request.backup_vault = backup_vault + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_backup_vault] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("backup_vault.name", request.backup_vault.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupvault.BackupVault, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup_vault( + self, + request: Optional[Union[backupvault.DeleteBackupVaultRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a BackupVault. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_delete_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupVaultRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest, dict]): + The request object. Message for deleting a BackupVault. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.DeleteBackupVaultRequest): + request = backupvault.DeleteBackupVaultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_backup_vault] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_data_sources( + self, + request: Optional[Union[backupvault.ListDataSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDataSourcesPager: + r"""Lists DataSources in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_data_sources(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListDataSourcesRequest, dict]): + The request object. Request message for listing + DataSources. + parent (str): + Required. The project and location for which to retrieve + data sources information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve data + sources for all locations, use "-" for the '{location}' + value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesPager: + Response message for listing + DataSources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.ListDataSourcesRequest): + request = backupvault.ListDataSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_data_sources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_source( + self, + request: Optional[Union[backupvault.GetDataSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.DataSource: + r"""Gets details of a DataSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetDataSourceRequest, dict]): + The request object. Request message for getting a + DataSource instance. + name (str): + Required. Name of the data source resource name, in the + format + 'projects/{project_id}/locations/{location}/backupVaults/{resource_name}/dataSource/{resource_name}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.DataSource: + Message describing a DataSource + object. Datasource object used to + represent Datasource details for both + admin and basic view. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.GetDataSourceRequest): + request = backupvault.GetDataSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_data_source( + self, + request: Optional[Union[backupvault.UpdateDataSourceRequest, dict]] = None, + *, + data_source: Optional[backupvault.DataSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the settings of a DataSource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_update_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateDataSourceRequest( + ) + + # Make the request + operation = client.update_data_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.UpdateDataSourceRequest, dict]): + The request object. Request message for updating a data + source instance. + data_source (google.cloud.backupdr_v1beta.types.DataSource): + Required. The resource being updated + This corresponds to the ``data_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the DataSource resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.DataSource` Message describing a DataSource object. + Datasource object used to represent Datasource + details for both admin and basic view. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [data_source, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.UpdateDataSourceRequest): + request = backupvault.UpdateDataSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_source is not None: + request.data_source = data_source + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_data_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("data_source.name", request.data_source.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupvault.DataSource, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backups( + self, + request: Optional[Union[backupvault.ListBackupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupsPager: + r"""Lists Backups in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_backups(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListBackupsRequest, dict]): + The request object. Request message for listing Backups. + parent (str): + Required. The project and location for which to retrieve + backup information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve data + sources for all locations, use "-" for the '{location}' + value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsPager: + Response message for listing Backups. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.ListBackupsRequest): + request = backupvault.ListBackupsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_backups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBackupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def fetch_backups_for_resource_type( + self, + request: Optional[ + Union[backupvault.FetchBackupsForResourceTypeRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + resource_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchBackupsForResourceTypePager: + r"""Fetch Backups for a given resource type. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_fetch_backups_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backups_for_resource_type(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest, dict]): + The request object. Request for the + FetchBackupsForResourceType method. + parent (str): + Required. Datasources are the parent + resource for the backups. Format: + + projects/{project}/locations/{location}/backupVaults/{backupVaultId}/dataSources/{datasourceId} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource_type (str): + Required. The type of the GCP + resource. Ex: + sqladmin.googleapis.com/Instance + + This corresponds to the ``resource_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypePager: + Response for the + FetchBackupsForResourceType method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, resource_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.FetchBackupsForResourceTypeRequest): + request = backupvault.FetchBackupsForResourceTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource_type is not None: + request.resource_type = resource_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_backups_for_resource_type + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchBackupsForResourceTypePager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_backup( + self, + request: Optional[Union[backupvault.GetBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.Backup: + r"""Gets details of a Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetBackupRequest, dict]): + The request object. Request message for getting a Backup. + name (str): + Required. Name of the data source resource name, in the + format + 'projects/{project_id}/locations/{location}/backupVaults/{backupVault}/dataSources/{datasource}/backups/{backup}' + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.Backup: + Message describing a Backup object. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.GetBackupRequest): + request = backupvault.GetBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_backup( + self, + request: Optional[Union[backupvault.UpdateBackupRequest, dict]] = None, + *, + backup: Optional[backupvault.Backup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the settings of a Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_update_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupRequest( + ) + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.UpdateBackupRequest, dict]): + The request object. Request message for updating a + Backup. + backup (google.cloud.backupdr_v1beta.types.Backup): + Required. The resource being updated + This corresponds to the ``backup`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.Backup` + Message describing a Backup object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.UpdateBackupRequest): + request = backupvault.UpdateBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup is not None: + request.backup = backup + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("backup.name", request.backup.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupvault.Backup, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_backup( + self, + request: Optional[Union[backupvault.DeleteBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_delete_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteBackupRequest, dict]): + The request object. Message for deleting a Backup. + name (str): + Required. Name of the resource. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.Backup` + Message describing a Backup object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.DeleteBackupRequest): + request = backupvault.DeleteBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupvault.Backup, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def restore_backup( + self, + request: Optional[Union[backupvault.RestoreBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Restore from a Backup + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_restore_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + compute_instance_target_environment = backupdr_v1beta.ComputeInstanceTargetEnvironment() + compute_instance_target_environment.project = "project_value" + compute_instance_target_environment.zone = "zone_value" + + request = backupdr_v1beta.RestoreBackupRequest( + compute_instance_target_environment=compute_instance_target_environment, + name="name_value", + ) + + # Make the request + operation = client.restore_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.RestoreBackupRequest, dict]): + The request object. Request message for restoring from a + Backup. + name (str): + Required. The resource name of the Backup instance, in + the format + 'projects/*/locations/*/backupVaults/*/dataSources/*/backups/'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.RestoreBackupResponse` + Response message for restoring from a Backup. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupvault.RestoreBackupRequest): + request = backupvault.RestoreBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupvault.RestoreBackupResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_backup_plan( + self, + request: Optional[Union[backupplan.CreateBackupPlanRequest, dict]] = None, + *, + parent: Optional[str] = None, + backup_plan: Optional[backupplan.BackupPlan] = None, + backup_plan_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Create a BackupPlan + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.CreateBackupPlanRequest( + parent="parent_value", + backup_plan_id="backup_plan_id_value", + backup_plan=backup_plan, + ) + + # Make the request + operation = client.create_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateBackupPlanRequest, dict]): + The request object. The request message for creating a ``BackupPlan``. + parent (str): + Required. The ``BackupPlan`` project and location in the + format ``projects/{project}/locations/{location}``. In + Google Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan (google.cloud.backupdr_v1beta.types.BackupPlan): + Required. The ``BackupPlan`` resource object to create. + This corresponds to the ``backup_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan_id (str): + Required. The name of the ``BackupPlan`` to create. The + name must be unique for the specified project and + location.The name must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, or + hyphens. Pattern, /[a-z][a-z0-9-]{,62}/. + + This corresponds to the ``backup_plan_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlan` A BackupPlan specifies some common fields, such as description as well + as one or more BackupRule messages. Each BackupRule + has a retention policy and defines a schedule by + which the system is to perform backup workloads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, backup_plan, backup_plan_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.CreateBackupPlanRequest): + request = backupplan.CreateBackupPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup_plan is not None: + request.backup_plan = backup_plan + if backup_plan_id is not None: + request.backup_plan_id = backup_plan_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_backup_plan] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupplan.BackupPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_backup_plan( + self, + request: Optional[Union[backupplan.UpdateBackupPlanRequest, dict]] = None, + *, + backup_plan: Optional[backupplan.BackupPlan] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Update a BackupPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_update_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.UpdateBackupPlanRequest( + backup_plan=backup_plan, + ) + + # Make the request + operation = client.update_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.UpdateBackupPlanRequest, dict]): + The request object. Request message for updating a backup + plan. + backup_plan (google.cloud.backupdr_v1beta.types.BackupPlan): + Required. The resource being updated + This corresponds to the ``backup_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + BackupPlan resource by the update. The fields specified + in the update_mask are relative to the resource, not the + full request. A field will be overwritten if it is in + the mask. If the user does not provide a mask then the + request will fail. Currently, these fields are supported + in update: description, schedules, retention period, + adding and removing Backup Rules. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlan` A BackupPlan specifies some common fields, such as description as well + as one or more BackupRule messages. Each BackupRule + has a retention policy and defines a schedule by + which the system is to perform backup workloads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup_plan, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.UpdateBackupPlanRequest): + request = backupplan.UpdateBackupPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup_plan is not None: + request.backup_plan = backup_plan + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_backup_plan] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("backup_plan.name", request.backup_plan.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupplan.BackupPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_backup_plan( + self, + request: Optional[Union[backupplan.GetBackupPlanRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlan: + r"""Gets details of a single BackupPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_plan(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetBackupPlanRequest, dict]): + The request object. The request message for getting a ``BackupPlan``. + name (str): + Required. The resource name of the ``BackupPlan`` to + retrieve. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupPlan: + A BackupPlan specifies some common fields, such as description as well + as one or more BackupRule messages. Each BackupRule + has a retention policy and defines a schedule by + which the system is to perform backup workloads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.GetBackupPlanRequest): + request = backupplan.GetBackupPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_backup_plan] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_backup_plans( + self, + request: Optional[Union[backupplan.ListBackupPlansRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupPlansPager: + r"""Lists BackupPlans in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_backup_plans(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plans(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListBackupPlansRequest, dict]): + The request object. The request message for getting a list ``BackupPlan``. + parent (str): + Required. The project and location for which to retrieve + ``BackupPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for e.g. **us-central1**. To retrieve backup + plans for all locations, use "-" for the ``{location}`` + value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansPager: + The response message for getting a list of BackupPlan. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.ListBackupPlansRequest): + request = backupplan.ListBackupPlansRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_backup_plans] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBackupPlansPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_backup_plan( + self, + request: Optional[Union[backupplan.DeleteBackupPlanRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single BackupPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_delete_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest, dict]): + The request object. The request message for deleting a ``BackupPlan``. + name (str): + Required. The resource name of the ``BackupPlan`` to + delete. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.DeleteBackupPlanRequest): + request = backupplan.DeleteBackupPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_backup_plan] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_backup_plan_revision( + self, + request: Optional[Union[backupplan.GetBackupPlanRevisionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlanRevision: + r"""Gets details of a single BackupPlanRevision. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_backup_plan_revision(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_plan_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest, dict]): + The request object. The request message for getting a + ``BackupPlanRevision``. + name (str): + Required. The resource name of the + ``BackupPlanRevision`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupPlanRevision: + BackupPlanRevision represents a snapshot of a BackupPlan at a point in + time. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.GetBackupPlanRevisionRequest): + request = backupplan.GetBackupPlanRevisionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_backup_plan_revision] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_backup_plan_revisions( + self, + request: Optional[ + Union[backupplan.ListBackupPlanRevisionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupPlanRevisionsPager: + r"""Lists BackupPlanRevisions in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_backup_plan_revisions(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest, dict]): + The request object. The request message for getting a list of + ``BackupPlanRevision``. + parent (str): + Required. The project and location for which to retrieve + ``BackupPlanRevisions`` information. Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}``. + In Google Cloud Backup and DR, locations map to Google + Cloud regions, for e.g. **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsPager: + The response message for getting a list of + BackupPlanRevision. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplan.ListBackupPlanRevisionsRequest): + request = backupplan.ListBackupPlanRevisionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_backup_plan_revisions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBackupPlanRevisionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.CreateBackupPlanAssociationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + backup_plan_association: Optional[ + backupplanassociation.BackupPlanAssociation + ] = None, + backup_plan_association_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Create a BackupPlanAssociation + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = client.create_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateBackupPlanAssociationRequest, dict]): + The request object. Request message for creating a backup + plan. + parent (str): + Required. The backup plan association project and + location in the format + ``projects/{project_id}/locations/{location}``. In + Backup and DR locations map to Google Cloud regions, for + example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan_association (google.cloud.backupdr_v1beta.types.BackupPlanAssociation): + Required. The resource being created + This corresponds to the ``backup_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + backup_plan_association_id (str): + Required. The name of the backup plan + association to create. The name must be + unique for the specified project and + location. + + This corresponds to the ``backup_plan_association_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation` A BackupPlanAssociation represents a single BackupPlanAssociation which + contains details like workload, backup plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, backup_plan_association, backup_plan_association_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.CreateBackupPlanAssociationRequest + ): + request = backupplanassociation.CreateBackupPlanAssociationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if backup_plan_association is not None: + request.backup_plan_association = backup_plan_association + if backup_plan_association_id is not None: + request.backup_plan_association_id = backup_plan_association_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupplanassociation.BackupPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.UpdateBackupPlanAssociationRequest, dict] + ] = None, + *, + backup_plan_association: Optional[ + backupplanassociation.BackupPlanAssociation + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Update a BackupPlanAssociation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_update_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.UpdateBackupPlanAssociationRequest( + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = client.update_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.UpdateBackupPlanAssociationRequest, dict]): + The request object. Request message for updating a backup + plan association. + backup_plan_association (google.cloud.backupdr_v1beta.types.BackupPlanAssociation): + Required. The resource being updated + This corresponds to the ``backup_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + BackupPlanAssociation resource by the update. The fields + specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then the request will fail. Currently + backup_plan_association.backup_plan is the only + supported field. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation` A BackupPlanAssociation represents a single BackupPlanAssociation which + contains details like workload, backup plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [backup_plan_association, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.UpdateBackupPlanAssociationRequest + ): + request = backupplanassociation.UpdateBackupPlanAssociationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if backup_plan_association is not None: + request.backup_plan_association = backup_plan_association + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "backup_plan_association.name", + request.backup_plan_association.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupplanassociation.BackupPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.GetBackupPlanAssociationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.BackupPlanAssociation: + r"""Gets details of a single BackupPlanAssociation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_plan_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest, dict]): + The request object. Request message for getting a + BackupPlanAssociation resource. + name (str): + Required. Name of the backup plan association resource, + in the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BackupPlanAssociation: + A BackupPlanAssociation represents a + single BackupPlanAssociation which + contains details like workload, backup + plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.GetBackupPlanAssociationRequest + ): + request = backupplanassociation.GetBackupPlanAssociationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_backup_plan_associations( + self, + request: Optional[ + Union[backupplanassociation.ListBackupPlanAssociationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBackupPlanAssociationsPager: + r"""Lists BackupPlanAssociations in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_backup_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_associations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest, dict]): + The request object. Request message for List + BackupPlanAssociation + parent (str): + Required. The project and location for which to retrieve + backup Plan Associations information, in the format + ``projects/{project_id}/locations/{location}``. In + Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. To retrieve backup plan + associations for all locations, use "-" for the + ``{location}`` value. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsPager: + Response message for List + BackupPlanAssociation + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.ListBackupPlanAssociationsRequest + ): + request = backupplanassociation.ListBackupPlanAssociationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_backup_plan_associations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBackupPlanAssociationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def fetch_backup_plan_associations_for_resource_type( + self, + request: Optional[ + Union[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + resource_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchBackupPlanAssociationsForResourceTypePager: + r"""List BackupPlanAssociations for a given resource + type. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_fetch_backup_plan_associations_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backup_plan_associations_for_resource_type(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest, dict]): + The request object. Request for the + FetchBackupPlanAssociationsForResourceType + method. + parent (str): + Required. The parent resource name. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource_type (str): + Required. The type of the Google + Cloud resource. Ex: + sql.googleapis.com/Instance + + This corresponds to the ``resource_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypePager: + Response for the + FetchBackupPlanAssociationsForResourceType + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, resource_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + ): + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource_type is not None: + request.resource_type = resource_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_backup_plan_associations_for_resource_type + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchBackupPlanAssociationsForResourceTypePager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_backup_plan_association( + self, + request: Optional[ + Union[backupplanassociation.DeleteBackupPlanAssociationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single BackupPlanAssociation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_delete_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest, dict]): + The request object. Request message for deleting a backup + plan association. + name (str): + Required. Name of the backup plan association resource, + in the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, backupplanassociation.DeleteBackupPlanAssociationRequest + ): + request = backupplanassociation.DeleteBackupPlanAssociationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_backup_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def trigger_backup( + self, + request: Optional[ + Union[backupplanassociation.TriggerBackupRequest, dict] + ] = None, + *, + name: Optional[str] = None, + rule_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Triggers a new Backup. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_trigger_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.TriggerBackupRequest, dict]): + The request object. Request message for triggering a + backup. + name (str): + Required. Name of the backup plan association resource, + in the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rule_id (str): + Optional. backup rule_id for which a backup needs to be + triggered. If not specified, on-demand backup with + custom retention will be triggered. + + This corresponds to the ``rule_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.BackupPlanAssociation` A BackupPlanAssociation represents a single BackupPlanAssociation which + contains details like workload, backup plan etc + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, rule_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupplanassociation.TriggerBackupRequest): + request = backupplanassociation.TriggerBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if rule_id is not None: + request.rule_id = rule_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.trigger_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupplanassociation.BackupPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_data_source_reference( + self, + request: Optional[ + Union[datasourcereference.GetDataSourceReferenceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasourcereference.DataSourceReference: + r"""Gets details of a single DataSourceReference. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_data_source_reference(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceReferenceRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_source_reference(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest, dict]): + The request object. Request for the + GetDataSourceReference method. + name (str): + Required. The name of the DataSourceReference to + retrieve. Format: + projects/{project}/locations/{location}/dataSourceReferences/{data_source_reference} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.DataSourceReference: + DataSourceReference is a reference to + a DataSource resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasourcereference.GetDataSourceReferenceRequest): + request = datasourcereference.GetDataSourceReferenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_data_source_reference + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_data_source_references( + self, + request: Optional[ + Union[datasourcereference.ListDataSourceReferencesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDataSourceReferencesPager: + r"""Lists DataSourceReferences for a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_data_source_references(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourceReferencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_source_references(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest, dict]): + The request object. Request for the + ListDataSourceReferences method. + parent (str): + Required. The parent resource name. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesPager: + Response for the + ListDataSourceReferences method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, datasourcereference.ListDataSourceReferencesRequest): + request = datasourcereference.ListDataSourceReferencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_data_source_references + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataSourceReferencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def fetch_data_source_references_for_resource_type( + self, + request: Optional[ + Union[ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + resource_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchDataSourceReferencesForResourceTypePager: + r"""Fetch DataSourceReferences for a given project, + location and resource type. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_fetch_data_source_references_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_data_source_references_for_resource_type(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest, dict]): + The request object. Request for the + FetchDataSourceReferencesForResourceType + method. + parent (str): + Required. The parent resource name. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource_type (str): + Required. The type of the Google + Cloud resource. Ex: + sql.googleapis.com/Instance + + This corresponds to the ``resource_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypePager: + Response for the + FetchDataSourceReferencesForResourceType + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, resource_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, datasourcereference.FetchDataSourceReferencesForResourceTypeRequest + ): + request = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource_type is not None: + request.resource_type = resource_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_data_source_references_for_resource_type + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchDataSourceReferencesForResourceTypePager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def initialize_service( + self, + request: Optional[Union[backupdr.InitializeServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Initializes the service related config for a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_initialize_service(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + cloud_sql_instance_initialization_config = backupdr_v1beta.CloudSqlInstanceInitializationConfig() + cloud_sql_instance_initialization_config.edition = "ENTERPRISE_PLUS" + + request = backupdr_v1beta.InitializeServiceRequest( + cloud_sql_instance_initialization_config=cloud_sql_instance_initialization_config, + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.InitializeServiceRequest, dict]): + The request object. Request message for initializing the + service. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.InitializeServiceResponse` + Response message for initializing the service. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, backupdr.InitializeServiceRequest): + request = backupdr.InitializeServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.initialize_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupdr.InitializeServiceResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.CreateAutoProtectionPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + auto_protection_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new AutoProtectionPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1beta.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyRequest, dict]): + The request object. Request message for creating an + AutoProtectionPolicy. + parent (str): + Required. The parent resource where + this policy will be created. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy (google.cloud.backupdr_v1beta.types.AutoProtectionPolicy): + Required. The AutoProtectionPolicy + resource to create. + + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_id (str): + Required. The ID to use for the + policy. This will become the final + component of the policy's resource name. + + This corresponds to the ``auto_protection_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, auto_protection_policy, auto_protection_policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.CreateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if auto_protection_policy_id is not None: + request.auto_protection_policy_id = auto_protection_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_auto_protection_policies( + self, + request: Optional[ + Union[autoprotectionpolicy.ListAutoProtectionPoliciesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAutoProtectionPoliciesPager: + r"""Lists AutoProtectionPolicies for a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest, dict]): + The request object. Request message for + ListAutoProtectionPolicies. + parent (str): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesPager: + Response message for + ListAutoProtectionPolicies. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.ListAutoProtectionPoliciesRequest + ): + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_auto_protection_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAutoProtectionPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.GetAutoProtectionPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicy.AutoProtectionPolicy: + r"""Gets details of a single AutoProtectionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest, dict]): + The request object. Request message for getting an + AutoProtectionPolicy. + name (str): + Required. The name of the policy to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.AutoProtectionPolicy: + An AutoprotectionPolicy is a policy + resource designed to automate backup + management, moving from manual + per-resource protection to a bulk + approach. The policy dynamically + discovers and applies a specified backup + plan to all eligible resources that + match its defined scope and criteria. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autoprotectionpolicy.GetAutoProtectionPolicyRequest): + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, dict] + ] = None, + *, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single + AutoProtectionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1beta.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.UpdateAutoProtectionPolicyRequest, dict]): + The request object. Request message for updating an + AutoProtectionPolicy. + auto_protection_policy (google.cloud.backupdr_v1beta.types.AutoProtectionPolicy): + Required. The policy to update. + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the AutoProtectionPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [auto_protection_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.UpdateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("auto_protection_policy.name", request.auto_protection_policy.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single AutoProtectionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest, dict]): + The request object. Request message for deleting an + AutoProtectionPolicy. + name (str): + Required. The name of the policy to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicy.DeleteAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy_binding: Optional[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding + ] = None, + auto_protection_policy_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new AutoProtectionPolicyBinding in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1beta.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1beta.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyBindingRequest, dict]): + The request object. Request message for creating an + AutoProtectionPolicyBinding. + parent (str): + Required. The parent resource where this binding will be + created. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding (google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding): + Required. The + AutoProtectionPolicyBinding resource to + create. + + This corresponds to the ``auto_protection_policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding_id (str): + Required. The ID to use for the + binding. This will become the final + component of the binding's resource + name. + + This corresponds to the ``auto_protection_policy_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding` An AutoprotectionPolicyBinding (APPA) acts as the bridge between an + AutoprotectionPolicy and the scope (Project, Folder, + or Organization) where the policy should be applied. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + auto_protection_policy_binding, + auto_protection_policy_binding_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + ): + request = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy_binding is not None: + request.auto_protection_policy_binding = auto_protection_policy_binding + if auto_protection_policy_binding_id is not None: + request.auto_protection_policy_binding_id = ( + auto_protection_policy_binding_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, dict + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + r"""Returns the auto protection policy binding read from + the CCFE tables. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest, dict]): + The request object. Request message for getting an + AutoProtectionPolicyBinding. + name (str): + Required. The name of the binding to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding: + An AutoprotectionPolicyBinding (APPA) + acts as the bridge between an + AutoprotectionPolicy and the scope + (Project, Folder, or Organization) where + the policy should be applied. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest + ): + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_auto_protection_policy_bindings( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAutoProtectionPolicyBindingsPager: + r"""Returns the auto protection policy bindings read from + the CCFE tables. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest, dict]): + The request object. Request message for + ListAutoProtectionPolicyBindings. + parent (str): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsPager: + Response message for + ListAutoProtectionPolicyBindings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest + ): + request = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_auto_protection_policy_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAutoProtectionPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_applied_auto_protection_policies( + self, + request: Optional[ + Union[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAppliedAutoProtectionPoliciesPager: + r"""Lists AppliedAutoProtectionPolicies in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest, dict]): + The request object. Request message for listing + AppliedAutoProtectionPolicies. + parent (str): + Required. The project and location + for which to retrieve the list of + applied policies. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesPager: + Response message for + ListAppliedAutoProtectionPolicies. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + ): + request = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_applied_auto_protection_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAppliedAutoProtectionPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def initiate_delete_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.initiate_delete_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest, dict]): + The request object. Request message for initiating delete + of an AutoProtectionPolicyBinding. + name (str): + Required. The name of the binding to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding` An AutoprotectionPolicyBinding (APPA) acts as the bridge between an + AutoprotectionPolicy and the scope (Project, Folder, + or Organization) where the policy should be applied. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + ): + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.initiate_delete_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_binding_matching_resource( + self, + request: Optional[ + Union[bindingmatchingresource.GetBindingMatchingResourceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bindingmatchingresource.BindingMatchingResource: + r"""Gets details of a single Binding Matching Resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_get_binding_matching_resource(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBindingMatchingResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_binding_matching_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest, dict]): + The request object. Request message for getting a + BindingMatchingResource. + name (str): + Required. The name of the matching resource to retrieve. + Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.types.BindingMatchingResource: + BindingMatchingResource contains the + details of a resource that matches the + criteria of a binding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bindingmatchingresource.GetBindingMatchingResourceRequest + ): + request = bindingmatchingresource.GetBindingMatchingResourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_binding_matching_resource + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_binding_matching_resources( + self, + request: Optional[ + Union[bindingmatchingresource.ListBindingMatchingResourcesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBindingMatchingResourcesPager: + r"""Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest, dict]): + The request object. Request message for List + BindingMatchingResources. + parent (str): + Required. The project, location, auto protection policy + and binding for which to retrieve + ``BindingMatchingResources`` information. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}``. + In Google Cloud Backup and DR, locations map to Google + Cloud regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesPager: + The response message for getting a list of + BindingMatchingResources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, bindingmatchingresource.ListBindingMatchingResourcesRequest + ): + request = bindingmatchingresource.ListBindingMatchingResourcesRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_binding_matching_resources + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBindingMatchingResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "BackupDRClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("BackupDRClient",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/pagers.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/pagers.py new file mode 100644 index 000000000000..cb5b304189cd --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/pagers.py @@ -0,0 +1,2670 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + bindingmatchingresource, + datasourcereference, +) + + +class ListManagementServersPager: + """A pager for iterating through ``list_management_servers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListManagementServersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``management_servers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListManagementServers`` requests and continue to iterate + through the ``management_servers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListManagementServersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupdr.ListManagementServersResponse], + request: backupdr.ListManagementServersRequest, + response: backupdr.ListManagementServersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListManagementServersRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListManagementServersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupdr.ListManagementServersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupdr.ListManagementServersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupdr.ManagementServer]: + for page in self.pages: + yield from page.management_servers + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListManagementServersAsyncPager: + """A pager for iterating through ``list_management_servers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListManagementServersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``management_servers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListManagementServers`` requests and continue to iterate + through the ``management_servers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListManagementServersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[backupdr.ListManagementServersResponse]], + request: backupdr.ListManagementServersRequest, + response: backupdr.ListManagementServersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListManagementServersRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListManagementServersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupdr.ListManagementServersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[backupdr.ListManagementServersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupdr.ManagementServer]: + async def async_generator(): + async for page in self.pages: + for response in page.management_servers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupVaultsPager: + """A pager for iterating through ``list_backup_vaults`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupVaultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backup_vaults`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackupVaults`` requests and continue to iterate + through the ``backup_vaults`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupVaultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupvault.ListBackupVaultsResponse], + request: backupvault.ListBackupVaultsRequest, + response: backupvault.ListBackupVaultsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupVaultsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.ListBackupVaultsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupvault.ListBackupVaultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupvault.BackupVault]: + for page in self.pages: + yield from page.backup_vaults + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupVaultsAsyncPager: + """A pager for iterating through ``list_backup_vaults`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupVaultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backup_vaults`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackupVaults`` requests and continue to iterate + through the ``backup_vaults`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupVaultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[backupvault.ListBackupVaultsResponse]], + request: backupvault.ListBackupVaultsRequest, + response: backupvault.ListBackupVaultsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupVaultsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.ListBackupVaultsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[backupvault.ListBackupVaultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupvault.BackupVault]: + async def async_generator(): + async for page in self.pages: + for response in page.backup_vaults: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchUsableBackupVaultsPager: + """A pager for iterating through ``fetch_usable_backup_vaults`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backup_vaults`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchUsableBackupVaults`` requests and continue to iterate + through the ``backup_vaults`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupvault.FetchUsableBackupVaultsResponse], + request: backupvault.FetchUsableBackupVaultsRequest, + response: backupvault.FetchUsableBackupVaultsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.FetchUsableBackupVaultsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupvault.FetchUsableBackupVaultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupvault.BackupVault]: + for page in self.pages: + yield from page.backup_vaults + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchUsableBackupVaultsAsyncPager: + """A pager for iterating through ``fetch_usable_backup_vaults`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backup_vaults`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchUsableBackupVaults`` requests and continue to iterate + through the ``backup_vaults`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[backupvault.FetchUsableBackupVaultsResponse]], + request: backupvault.FetchUsableBackupVaultsRequest, + response: backupvault.FetchUsableBackupVaultsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.FetchUsableBackupVaultsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[backupvault.FetchUsableBackupVaultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupvault.BackupVault]: + async def async_generator(): + async for page in self.pages: + for response in page.backup_vaults: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDataSourcesPager: + """A pager for iterating through ``list_data_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListDataSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataSources`` requests and continue to iterate + through the ``data_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListDataSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupvault.ListDataSourcesResponse], + request: backupvault.ListDataSourcesRequest, + response: backupvault.ListDataSourcesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListDataSourcesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListDataSourcesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.ListDataSourcesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupvault.ListDataSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupvault.DataSource]: + for page in self.pages: + yield from page.data_sources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDataSourcesAsyncPager: + """A pager for iterating through ``list_data_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListDataSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataSources`` requests and continue to iterate + through the ``data_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListDataSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[backupvault.ListDataSourcesResponse]], + request: backupvault.ListDataSourcesRequest, + response: backupvault.ListDataSourcesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListDataSourcesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListDataSourcesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.ListDataSourcesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[backupvault.ListDataSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupvault.DataSource]: + async def async_generator(): + async for page in self.pages: + for response in page.data_sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupsPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupvault.ListBackupsResponse], + request: backupvault.ListBackupsRequest, + response: backupvault.ListBackupsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.ListBackupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupvault.ListBackupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupvault.Backup]: + for page in self.pages: + yield from page.backups + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupsAsyncPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[backupvault.ListBackupsResponse]], + request: backupvault.ListBackupsRequest, + response: backupvault.ListBackupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.ListBackupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[backupvault.ListBackupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupvault.Backup]: + async def async_generator(): + async for page in self.pages: + for response in page.backups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchBackupsForResourceTypePager: + """A pager for iterating through ``fetch_backups_for_resource_type`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchBackupsForResourceType`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupvault.FetchBackupsForResourceTypeResponse], + request: backupvault.FetchBackupsForResourceTypeRequest, + response: backupvault.FetchBackupsForResourceTypeResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.FetchBackupsForResourceTypeRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupvault.FetchBackupsForResourceTypeResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupvault.Backup]: + for page in self.pages: + yield from page.backups + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchBackupsForResourceTypeAsyncPager: + """A pager for iterating through ``fetch_backups_for_resource_type`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchBackupsForResourceType`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[backupvault.FetchBackupsForResourceTypeResponse] + ], + request: backupvault.FetchBackupsForResourceTypeRequest, + response: backupvault.FetchBackupsForResourceTypeResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupvault.FetchBackupsForResourceTypeRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[backupvault.FetchBackupsForResourceTypeResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupvault.Backup]: + async def async_generator(): + async for page in self.pages: + for response in page.backups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupPlansPager: + """A pager for iterating through ``list_backup_plans`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupPlansResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backup_plans`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackupPlans`` requests and continue to iterate + through the ``backup_plans`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupPlansResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupplan.ListBackupPlansResponse], + request: backupplan.ListBackupPlansRequest, + response: backupplan.ListBackupPlansResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupPlansRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupPlansResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupplan.ListBackupPlansRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupplan.ListBackupPlansResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupplan.BackupPlan]: + for page in self.pages: + yield from page.backup_plans + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupPlansAsyncPager: + """A pager for iterating through ``list_backup_plans`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupPlansResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backup_plans`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackupPlans`` requests and continue to iterate + through the ``backup_plans`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupPlansResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[backupplan.ListBackupPlansResponse]], + request: backupplan.ListBackupPlansRequest, + response: backupplan.ListBackupPlansResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupPlansRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupPlansResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupplan.ListBackupPlansRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[backupplan.ListBackupPlansResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupplan.BackupPlan]: + async def async_generator(): + async for page in self.pages: + for response in page.backup_plans: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupPlanRevisionsPager: + """A pager for iterating through ``list_backup_plan_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backup_plan_revisions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackupPlanRevisions`` requests and continue to iterate + through the ``backup_plan_revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupplan.ListBackupPlanRevisionsResponse], + request: backupplan.ListBackupPlanRevisionsRequest, + response: backupplan.ListBackupPlanRevisionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupplan.ListBackupPlanRevisionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[backupplan.ListBackupPlanRevisionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupplan.BackupPlanRevision]: + for page in self.pages: + yield from page.backup_plan_revisions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupPlanRevisionsAsyncPager: + """A pager for iterating through ``list_backup_plan_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backup_plan_revisions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackupPlanRevisions`` requests and continue to iterate + through the ``backup_plan_revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[backupplan.ListBackupPlanRevisionsResponse]], + request: backupplan.ListBackupPlanRevisionsRequest, + response: backupplan.ListBackupPlanRevisionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupplan.ListBackupPlanRevisionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[backupplan.ListBackupPlanRevisionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupplan.BackupPlanRevision]: + async def async_generator(): + async for page in self.pages: + for response in page.backup_plan_revisions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupPlanAssociationsPager: + """A pager for iterating through ``list_backup_plan_associations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backup_plan_associations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackupPlanAssociations`` requests and continue to iterate + through the ``backup_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., backupplanassociation.ListBackupPlanAssociationsResponse], + request: backupplanassociation.ListBackupPlanAssociationsRequest, + response: backupplanassociation.ListBackupPlanAssociationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupplanassociation.ListBackupPlanAssociationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[backupplanassociation.ListBackupPlanAssociationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupplanassociation.BackupPlanAssociation]: + for page in self.pages: + yield from page.backup_plan_associations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupPlanAssociationsAsyncPager: + """A pager for iterating through ``list_backup_plan_associations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backup_plan_associations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackupPlanAssociations`` requests and continue to iterate + through the ``backup_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[backupplanassociation.ListBackupPlanAssociationsResponse] + ], + request: backupplanassociation.ListBackupPlanAssociationsRequest, + response: backupplanassociation.ListBackupPlanAssociationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = backupplanassociation.ListBackupPlanAssociationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[backupplanassociation.ListBackupPlanAssociationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupplanassociation.BackupPlanAssociation]: + async def async_generator(): + async for page in self.pages: + for response in page.backup_plan_associations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchBackupPlanAssociationsForResourceTypePager: + """A pager for iterating through ``fetch_backup_plan_associations_for_resource_type`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backup_plan_associations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchBackupPlanAssociationsForResourceType`` requests and continue to iterate + through the ``backup_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + ], + request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[backupplanassociation.BackupPlanAssociation]: + for page in self.pages: + yield from page.backup_plan_associations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchBackupPlanAssociationsForResourceTypeAsyncPager: + """A pager for iterating through ``fetch_backup_plan_associations_for_resource_type`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backup_plan_associations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchBackupPlanAssociationsForResourceType`` requests and continue to iterate + through the ``backup_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse + ], + ], + request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[backupplanassociation.BackupPlanAssociation]: + async def async_generator(): + async for page in self.pages: + for response in page.backup_plan_associations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDataSourceReferencesPager: + """A pager for iterating through ``list_data_source_references`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListDataSourceReferencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_source_references`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataSourceReferences`` requests and continue to iterate + through the ``data_source_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListDataSourceReferencesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., datasourcereference.ListDataSourceReferencesResponse], + request: datasourcereference.ListDataSourceReferencesRequest, + response: datasourcereference.ListDataSourceReferencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListDataSourceReferencesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = datasourcereference.ListDataSourceReferencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[datasourcereference.ListDataSourceReferencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[datasourcereference.DataSourceReference]: + for page in self.pages: + yield from page.data_source_references + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDataSourceReferencesAsyncPager: + """A pager for iterating through ``list_data_source_references`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListDataSourceReferencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_source_references`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataSourceReferences`` requests and continue to iterate + through the ``data_source_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListDataSourceReferencesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[datasourcereference.ListDataSourceReferencesResponse] + ], + request: datasourcereference.ListDataSourceReferencesRequest, + response: datasourcereference.ListDataSourceReferencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListDataSourceReferencesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = datasourcereference.ListDataSourceReferencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[datasourcereference.ListDataSourceReferencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[datasourcereference.DataSourceReference]: + async def async_generator(): + async for page in self.pages: + for response in page.data_source_references: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchDataSourceReferencesForResourceTypePager: + """A pager for iterating through ``fetch_data_source_references_for_resource_type`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_source_references`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchDataSourceReferencesForResourceType`` requests and continue to iterate + through the ``data_source_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., datasourcereference.FetchDataSourceReferencesForResourceTypeResponse + ], + request: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + response: datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(request) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[datasourcereference.FetchDataSourceReferencesForResourceTypeResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[datasourcereference.DataSourceReference]: + for page in self.pages: + yield from page.data_source_references + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchDataSourceReferencesForResourceTypeAsyncPager: + """A pager for iterating through ``fetch_data_source_references_for_resource_type`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_source_references`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchDataSourceReferencesForResourceType`` requests and continue to iterate + through the ``data_source_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse + ], + ], + request: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + response: datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(request) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[datasourcereference.DataSourceReference]: + async def async_generator(): + async for page in self.pages: + for response in page.data_source_references: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPoliciesPager: + """A pager for iterating through ``list_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``auto_protection_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAutoProtectionPolicies`` requests and continue to iterate + through the ``auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., autoprotectionpolicy.ListAutoProtectionPoliciesResponse], + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[autoprotectionpolicy.ListAutoProtectionPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[autoprotectionpolicy.AutoProtectionPolicy]: + for page in self.pages: + yield from page.auto_protection_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPoliciesAsyncPager: + """A pager for iterating through ``list_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``auto_protection_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAutoProtectionPolicies`` requests and continue to iterate + through the ``auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[autoprotectionpolicy.ListAutoProtectionPoliciesResponse] + ], + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[autoprotectionpolicy.ListAutoProtectionPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[autoprotectionpolicy.AutoProtectionPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.auto_protection_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPolicyBindingsPager: + """A pager for iterating through ``list_auto_protection_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``auto_protection_policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAutoProtectionPolicyBindings`` requests and continue to iterate + through the ``auto_protection_policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ], + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(request) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__( + self, + ) -> Iterator[autoprotectionpolicybinding.AutoProtectionPolicyBinding]: + for page in self.pages: + yield from page.auto_protection_policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPolicyBindingsAsyncPager: + """A pager for iterating through ``list_auto_protection_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``auto_protection_policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAutoProtectionPolicyBindings`` requests and continue to iterate + through the ``auto_protection_policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ], + ], + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(request) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[autoprotectionpolicybinding.AutoProtectionPolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.auto_protection_policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAppliedAutoProtectionPoliciesPager: + """A pager for iterating through ``list_applied_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``applied_auto_protection_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAppliedAutoProtectionPolicies`` requests and continue to iterate + through the ``applied_auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__( + self, + ) -> Iterator[appliedautoprotectionpolicy.AppliedAutoProtectionPolicy]: + for page in self.pages: + yield from page.applied_auto_protection_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAppliedAutoProtectionPoliciesAsyncPager: + """A pager for iterating through ``list_applied_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``applied_auto_protection_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAppliedAutoProtectionPolicies`` requests and continue to iterate + through the ``applied_auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + ], + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[appliedautoprotectionpolicy.AppliedAutoProtectionPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.applied_auto_protection_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBindingMatchingResourcesPager: + """A pager for iterating through ``list_binding_matching_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``matching_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBindingMatchingResources`` requests and continue to iterate + through the ``matching_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., bindingmatchingresource.ListBindingMatchingResourcesResponse + ], + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, + response: bindingmatchingresource.ListBindingMatchingResourcesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bindingmatchingresource.ListBindingMatchingResourcesRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[bindingmatchingresource.ListBindingMatchingResourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[bindingmatchingresource.BindingMatchingResource]: + for page in self.pages: + yield from page.matching_resources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBindingMatchingResourcesAsyncPager: + """A pager for iterating through ``list_binding_matching_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``matching_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBindingMatchingResources`` requests and continue to iterate + through the ``matching_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[bindingmatchingresource.ListBindingMatchingResourcesResponse] + ], + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, + response: bindingmatchingresource.ListBindingMatchingResourcesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bindingmatchingresource.ListBindingMatchingResourcesRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[bindingmatchingresource.ListBindingMatchingResourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[bindingmatchingresource.BindingMatchingResource]: + async def async_generator(): + async for page in self.pages: + for response in page.matching_resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/README.rst b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/README.rst new file mode 100644 index 000000000000..209e6400429c --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``BackupDRTransport`` is the ABC for all transports. + +- public child ``BackupDRGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``BackupDRGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseBackupDRRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``BackupDRRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/__init__.py new file mode 100644 index 000000000000..a79523f5b823 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import BackupDRTransport +from .grpc import BackupDRGrpcTransport +from .grpc_asyncio import BackupDRGrpcAsyncIOTransport +from .rest import BackupDRRestInterceptor, BackupDRRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[BackupDRTransport]] +_transport_registry["grpc"] = BackupDRGrpcTransport +_transport_registry["grpc_asyncio"] = BackupDRGrpcAsyncIOTransport +_transport_registry["rest"] = BackupDRRestTransport + +__all__ = ( + "BackupDRTransport", + "BackupDRGrpcTransport", + "BackupDRGrpcAsyncIOTransport", + "BackupDRRestTransport", + "BackupDRRestInterceptor", +) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/base.py new file mode 100644 index 000000000000..09ef74bf20a5 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/base.py @@ -0,0 +1,1182 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.backupdr_v1beta import gapic_version as package_version +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + bindingmatchingresource, + datasourcereference, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class BackupDRTransport(abc.ABC): + """Abstract transport class for BackupDR.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "backupdr.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_management_servers: gapic_v1.method.wrap_method( + self.list_management_servers, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_management_server: gapic_v1.method.wrap_method( + self.get_management_server, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_management_server: gapic_v1.method.wrap_method( + self.create_management_server, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_management_server: gapic_v1.method.wrap_method( + self.delete_management_server, + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup_vault: gapic_v1.method.wrap_method( + self.create_backup_vault, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_backup_vaults: gapic_v1.method.wrap_method( + self.list_backup_vaults, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_usable_backup_vaults: gapic_v1.method.wrap_method( + self.fetch_usable_backup_vaults, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_backup_vault: gapic_v1.method.wrap_method( + self.get_backup_vault, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_backup_vault: gapic_v1.method.wrap_method( + self.update_backup_vault, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup_vault: gapic_v1.method.wrap_method( + self.delete_backup_vault, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_data_sources: gapic_v1.method.wrap_method( + self.list_data_sources, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_data_source: gapic_v1.method.wrap_method( + self.get_data_source, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_data_source: gapic_v1.method.wrap_method( + self.update_data_source, + default_timeout=60.0, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_backups_for_resource_type: gapic_v1.method.wrap_method( + self.fetch_backups_for_resource_type, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_backup: gapic_v1.method.wrap_method( + self.update_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.restore_backup: gapic_v1.method.wrap_method( + self.restore_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup_plan: gapic_v1.method.wrap_method( + self.create_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.update_backup_plan: gapic_v1.method.wrap_method( + self.update_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan: gapic_v1.method.wrap_method( + self.get_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plans: gapic_v1.method.wrap_method( + self.list_backup_plans, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup_plan: gapic_v1.method.wrap_method( + self.delete_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan_revision: gapic_v1.method.wrap_method( + self.get_backup_plan_revision, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plan_revisions: gapic_v1.method.wrap_method( + self.list_backup_plan_revisions, + default_timeout=None, + client_info=client_info, + ), + self.create_backup_plan_association: gapic_v1.method.wrap_method( + self.create_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.update_backup_plan_association: gapic_v1.method.wrap_method( + self.update_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan_association: gapic_v1.method.wrap_method( + self.get_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plan_associations: gapic_v1.method.wrap_method( + self.list_backup_plan_associations, + default_timeout=None, + client_info=client_info, + ), + self.fetch_backup_plan_associations_for_resource_type: gapic_v1.method.wrap_method( + self.fetch_backup_plan_associations_for_resource_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup_plan_association: gapic_v1.method.wrap_method( + self.delete_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.trigger_backup: gapic_v1.method.wrap_method( + self.trigger_backup, + default_timeout=None, + client_info=client_info, + ), + self.get_data_source_reference: gapic_v1.method.wrap_method( + self.get_data_source_reference, + default_timeout=None, + client_info=client_info, + ), + self.list_data_source_references: gapic_v1.method.wrap_method( + self.list_data_source_references, + default_timeout=None, + client_info=client_info, + ), + self.fetch_data_source_references_for_resource_type: gapic_v1.method.wrap_method( + self.fetch_data_source_references_for_resource_type, + default_timeout=None, + client_info=client_info, + ), + self.initialize_service: gapic_v1.method.wrap_method( + self.initialize_service, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_auto_protection_policy: gapic_v1.method.wrap_method( + self.create_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_auto_protection_policies: gapic_v1.method.wrap_method( + self.list_auto_protection_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_auto_protection_policy: gapic_v1.method.wrap_method( + self.get_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_auto_protection_policy: gapic_v1.method.wrap_method( + self.update_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_auto_protection_policy: gapic_v1.method.wrap_method( + self.delete_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_auto_protection_policy_binding: gapic_v1.method.wrap_method( + self.create_auto_protection_policy_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_auto_protection_policy_binding: gapic_v1.method.wrap_method( + self.get_auto_protection_policy_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_auto_protection_policy_bindings: gapic_v1.method.wrap_method( + self.list_auto_protection_policy_bindings, + default_timeout=None, + client_info=client_info, + ), + self.list_applied_auto_protection_policies: gapic_v1.method.wrap_method( + self.list_applied_auto_protection_policies, + default_timeout=None, + client_info=client_info, + ), + self.initiate_delete_auto_protection_policy_binding: gapic_v1.method.wrap_method( + self.initiate_delete_auto_protection_policy_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_binding_matching_resource: gapic_v1.method.wrap_method( + self.get_binding_matching_resource, + default_timeout=None, + client_info=client_info, + ), + self.list_binding_matching_resources: gapic_v1.method.wrap_method( + self.list_binding_matching_resources, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_management_servers( + self, + ) -> Callable[ + [backupdr.ListManagementServersRequest], + Union[ + backupdr.ListManagementServersResponse, + Awaitable[backupdr.ListManagementServersResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_management_server( + self, + ) -> Callable[ + [backupdr.GetManagementServerRequest], + Union[backupdr.ManagementServer, Awaitable[backupdr.ManagementServer]], + ]: + raise NotImplementedError() + + @property + def create_management_server( + self, + ) -> Callable[ + [backupdr.CreateManagementServerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_management_server( + self, + ) -> Callable[ + [backupdr.DeleteManagementServerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_backup_vault( + self, + ) -> Callable[ + [backupvault.CreateBackupVaultRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_backup_vaults( + self, + ) -> Callable[ + [backupvault.ListBackupVaultsRequest], + Union[ + backupvault.ListBackupVaultsResponse, + Awaitable[backupvault.ListBackupVaultsResponse], + ], + ]: + raise NotImplementedError() + + @property + def fetch_usable_backup_vaults( + self, + ) -> Callable[ + [backupvault.FetchUsableBackupVaultsRequest], + Union[ + backupvault.FetchUsableBackupVaultsResponse, + Awaitable[backupvault.FetchUsableBackupVaultsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_backup_vault( + self, + ) -> Callable[ + [backupvault.GetBackupVaultRequest], + Union[backupvault.BackupVault, Awaitable[backupvault.BackupVault]], + ]: + raise NotImplementedError() + + @property + def update_backup_vault( + self, + ) -> Callable[ + [backupvault.UpdateBackupVaultRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_backup_vault( + self, + ) -> Callable[ + [backupvault.DeleteBackupVaultRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_data_sources( + self, + ) -> Callable[ + [backupvault.ListDataSourcesRequest], + Union[ + backupvault.ListDataSourcesResponse, + Awaitable[backupvault.ListDataSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_data_source( + self, + ) -> Callable[ + [backupvault.GetDataSourceRequest], + Union[backupvault.DataSource, Awaitable[backupvault.DataSource]], + ]: + raise NotImplementedError() + + @property + def update_data_source( + self, + ) -> Callable[ + [backupvault.UpdateDataSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_backups( + self, + ) -> Callable[ + [backupvault.ListBackupsRequest], + Union[ + backupvault.ListBackupsResponse, Awaitable[backupvault.ListBackupsResponse] + ], + ]: + raise NotImplementedError() + + @property + def fetch_backups_for_resource_type( + self, + ) -> Callable[ + [backupvault.FetchBackupsForResourceTypeRequest], + Union[ + backupvault.FetchBackupsForResourceTypeResponse, + Awaitable[backupvault.FetchBackupsForResourceTypeResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_backup( + self, + ) -> Callable[ + [backupvault.GetBackupRequest], + Union[backupvault.Backup, Awaitable[backupvault.Backup]], + ]: + raise NotImplementedError() + + @property + def update_backup( + self, + ) -> Callable[ + [backupvault.UpdateBackupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_backup( + self, + ) -> Callable[ + [backupvault.DeleteBackupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def restore_backup( + self, + ) -> Callable[ + [backupvault.RestoreBackupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_backup_plan( + self, + ) -> Callable[ + [backupplan.CreateBackupPlanRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_backup_plan( + self, + ) -> Callable[ + [backupplan.UpdateBackupPlanRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_backup_plan( + self, + ) -> Callable[ + [backupplan.GetBackupPlanRequest], + Union[backupplan.BackupPlan, Awaitable[backupplan.BackupPlan]], + ]: + raise NotImplementedError() + + @property + def list_backup_plans( + self, + ) -> Callable[ + [backupplan.ListBackupPlansRequest], + Union[ + backupplan.ListBackupPlansResponse, + Awaitable[backupplan.ListBackupPlansResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_backup_plan( + self, + ) -> Callable[ + [backupplan.DeleteBackupPlanRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_backup_plan_revision( + self, + ) -> Callable[ + [backupplan.GetBackupPlanRevisionRequest], + Union[backupplan.BackupPlanRevision, Awaitable[backupplan.BackupPlanRevision]], + ]: + raise NotImplementedError() + + @property + def list_backup_plan_revisions( + self, + ) -> Callable[ + [backupplan.ListBackupPlanRevisionsRequest], + Union[ + backupplan.ListBackupPlanRevisionsResponse, + Awaitable[backupplan.ListBackupPlanRevisionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.CreateBackupPlanAssociationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.UpdateBackupPlanAssociationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.GetBackupPlanAssociationRequest], + Union[ + backupplanassociation.BackupPlanAssociation, + Awaitable[backupplanassociation.BackupPlanAssociation], + ], + ]: + raise NotImplementedError() + + @property + def list_backup_plan_associations( + self, + ) -> Callable[ + [backupplanassociation.ListBackupPlanAssociationsRequest], + Union[ + backupplanassociation.ListBackupPlanAssociationsResponse, + Awaitable[backupplanassociation.ListBackupPlanAssociationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def fetch_backup_plan_associations_for_resource_type( + self, + ) -> Callable[ + [backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest], + Union[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + Awaitable[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def delete_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.DeleteBackupPlanAssociationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def trigger_backup( + self, + ) -> Callable[ + [backupplanassociation.TriggerBackupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_data_source_reference( + self, + ) -> Callable[ + [datasourcereference.GetDataSourceReferenceRequest], + Union[ + datasourcereference.DataSourceReference, + Awaitable[datasourcereference.DataSourceReference], + ], + ]: + raise NotImplementedError() + + @property + def list_data_source_references( + self, + ) -> Callable[ + [datasourcereference.ListDataSourceReferencesRequest], + Union[ + datasourcereference.ListDataSourceReferencesResponse, + Awaitable[datasourcereference.ListDataSourceReferencesResponse], + ], + ]: + raise NotImplementedError() + + @property + def fetch_data_source_references_for_resource_type( + self, + ) -> Callable[ + [datasourcereference.FetchDataSourceReferencesForResourceTypeRequest], + Union[ + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + Awaitable[ + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def initialize_service( + self, + ) -> Callable[ + [backupdr.InitializeServiceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + Union[ + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + Awaitable[autoprotectionpolicy.ListAutoProtectionPoliciesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + Union[ + autoprotectionpolicy.AutoProtectionPolicy, + Awaitable[autoprotectionpolicy.AutoProtectionPolicy], + ], + ]: + raise NotImplementedError() + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + Union[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + Awaitable[autoprotectionpolicybinding.AutoProtectionPolicyBinding], + ], + ]: + raise NotImplementedError() + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + Union[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + Awaitable[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + Union[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + Awaitable[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_binding_matching_resource( + self, + ) -> Callable[ + [bindingmatchingresource.GetBindingMatchingResourceRequest], + Union[ + bindingmatchingresource.BindingMatchingResource, + Awaitable[bindingmatchingresource.BindingMatchingResource], + ], + ]: + raise NotImplementedError() + + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + Union[ + bindingmatchingresource.ListBindingMatchingResourcesResponse, + Awaitable[bindingmatchingresource.ListBindingMatchingResourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("BackupDRTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc.py new file mode 100644 index 000000000000..2a912a980bf1 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc.py @@ -0,0 +1,1987 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + bindingmatchingresource, + datasourcereference, +) + +from .base import DEFAULT_CLIENT_INFO, BackupDRTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BackupDRGrpcTransport(BackupDRTransport): + """gRPC backend transport for BackupDR. + + The BackupDR Service + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_management_servers( + self, + ) -> Callable[ + [backupdr.ListManagementServersRequest], backupdr.ListManagementServersResponse + ]: + r"""Return a callable for the list management servers method over gRPC. + + Lists ManagementServers in a given project and + location. + + Returns: + Callable[[~.ListManagementServersRequest], + ~.ListManagementServersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_management_servers" not in self._stubs: + self._stubs["list_management_servers"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListManagementServers", + request_serializer=backupdr.ListManagementServersRequest.serialize, + response_deserializer=backupdr.ListManagementServersResponse.deserialize, + ) + return self._stubs["list_management_servers"] + + @property + def get_management_server( + self, + ) -> Callable[[backupdr.GetManagementServerRequest], backupdr.ManagementServer]: + r"""Return a callable for the get management server method over gRPC. + + Gets details of a single ManagementServer. + + Returns: + Callable[[~.GetManagementServerRequest], + ~.ManagementServer]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_management_server" not in self._stubs: + self._stubs["get_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetManagementServer", + request_serializer=backupdr.GetManagementServerRequest.serialize, + response_deserializer=backupdr.ManagementServer.deserialize, + ) + return self._stubs["get_management_server"] + + @property + def create_management_server( + self, + ) -> Callable[[backupdr.CreateManagementServerRequest], operations_pb2.Operation]: + r"""Return a callable for the create management server method over gRPC. + + Creates a new ManagementServer in a given project and + location. + + Returns: + Callable[[~.CreateManagementServerRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_management_server" not in self._stubs: + self._stubs["create_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateManagementServer", + request_serializer=backupdr.CreateManagementServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_management_server"] + + @property + def delete_management_server( + self, + ) -> Callable[[backupdr.DeleteManagementServerRequest], operations_pb2.Operation]: + r"""Return a callable for the delete management server method over gRPC. + + Deletes a single ManagementServer. + + Returns: + Callable[[~.DeleteManagementServerRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_management_server" not in self._stubs: + self._stubs["delete_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteManagementServer", + request_serializer=backupdr.DeleteManagementServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_management_server"] + + @property + def create_backup_vault( + self, + ) -> Callable[[backupvault.CreateBackupVaultRequest], operations_pb2.Operation]: + r"""Return a callable for the create backup vault method over gRPC. + + Creates a new BackupVault in a given project and + location. + + Returns: + Callable[[~.CreateBackupVaultRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_backup_vault" not in self._stubs: + self._stubs["create_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateBackupVault", + request_serializer=backupvault.CreateBackupVaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_backup_vault"] + + @property + def list_backup_vaults( + self, + ) -> Callable[ + [backupvault.ListBackupVaultsRequest], backupvault.ListBackupVaultsResponse + ]: + r"""Return a callable for the list backup vaults method over gRPC. + + Lists BackupVaults in a given project and location. + + Returns: + Callable[[~.ListBackupVaultsRequest], + ~.ListBackupVaultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_vaults" not in self._stubs: + self._stubs["list_backup_vaults"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupVaults", + request_serializer=backupvault.ListBackupVaultsRequest.serialize, + response_deserializer=backupvault.ListBackupVaultsResponse.deserialize, + ) + return self._stubs["list_backup_vaults"] + + @property + def fetch_usable_backup_vaults( + self, + ) -> Callable[ + [backupvault.FetchUsableBackupVaultsRequest], + backupvault.FetchUsableBackupVaultsResponse, + ]: + r"""Return a callable for the fetch usable backup vaults method over gRPC. + + FetchUsableBackupVaults lists usable BackupVaults in + a given project and location. Usable BackupVault are the + ones that user has backupdr.backupVaults.get permission. + + Returns: + Callable[[~.FetchUsableBackupVaultsRequest], + ~.FetchUsableBackupVaultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_usable_backup_vaults" not in self._stubs: + self._stubs["fetch_usable_backup_vaults"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchUsableBackupVaults", + request_serializer=backupvault.FetchUsableBackupVaultsRequest.serialize, + response_deserializer=backupvault.FetchUsableBackupVaultsResponse.deserialize, + ) + ) + return self._stubs["fetch_usable_backup_vaults"] + + @property + def get_backup_vault( + self, + ) -> Callable[[backupvault.GetBackupVaultRequest], backupvault.BackupVault]: + r"""Return a callable for the get backup vault method over gRPC. + + Gets details of a BackupVault. + + Returns: + Callable[[~.GetBackupVaultRequest], + ~.BackupVault]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_vault" not in self._stubs: + self._stubs["get_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupVault", + request_serializer=backupvault.GetBackupVaultRequest.serialize, + response_deserializer=backupvault.BackupVault.deserialize, + ) + return self._stubs["get_backup_vault"] + + @property + def update_backup_vault( + self, + ) -> Callable[[backupvault.UpdateBackupVaultRequest], operations_pb2.Operation]: + r"""Return a callable for the update backup vault method over gRPC. + + Updates the settings of a BackupVault. + + Returns: + Callable[[~.UpdateBackupVaultRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup_vault" not in self._stubs: + self._stubs["update_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackupVault", + request_serializer=backupvault.UpdateBackupVaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_backup_vault"] + + @property + def delete_backup_vault( + self, + ) -> Callable[[backupvault.DeleteBackupVaultRequest], operations_pb2.Operation]: + r"""Return a callable for the delete backup vault method over gRPC. + + Deletes a BackupVault. + + Returns: + Callable[[~.DeleteBackupVaultRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup_vault" not in self._stubs: + self._stubs["delete_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackupVault", + request_serializer=backupvault.DeleteBackupVaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup_vault"] + + @property + def list_data_sources( + self, + ) -> Callable[ + [backupvault.ListDataSourcesRequest], backupvault.ListDataSourcesResponse + ]: + r"""Return a callable for the list data sources method over gRPC. + + Lists DataSources in a given project and location. + + Returns: + Callable[[~.ListDataSourcesRequest], + ~.ListDataSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_data_sources" not in self._stubs: + self._stubs["list_data_sources"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListDataSources", + request_serializer=backupvault.ListDataSourcesRequest.serialize, + response_deserializer=backupvault.ListDataSourcesResponse.deserialize, + ) + return self._stubs["list_data_sources"] + + @property + def get_data_source( + self, + ) -> Callable[[backupvault.GetDataSourceRequest], backupvault.DataSource]: + r"""Return a callable for the get data source method over gRPC. + + Gets details of a DataSource. + + Returns: + Callable[[~.GetDataSourceRequest], + ~.DataSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_data_source" not in self._stubs: + self._stubs["get_data_source"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetDataSource", + request_serializer=backupvault.GetDataSourceRequest.serialize, + response_deserializer=backupvault.DataSource.deserialize, + ) + return self._stubs["get_data_source"] + + @property + def update_data_source( + self, + ) -> Callable[[backupvault.UpdateDataSourceRequest], operations_pb2.Operation]: + r"""Return a callable for the update data source method over gRPC. + + Updates the settings of a DataSource. + + Returns: + Callable[[~.UpdateDataSourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_data_source" not in self._stubs: + self._stubs["update_data_source"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateDataSource", + request_serializer=backupvault.UpdateDataSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_data_source"] + + @property + def list_backups( + self, + ) -> Callable[[backupvault.ListBackupsRequest], backupvault.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + Returns: + Callable[[~.ListBackupsRequest], + ~.ListBackupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backups" not in self._stubs: + self._stubs["list_backups"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackups", + request_serializer=backupvault.ListBackupsRequest.serialize, + response_deserializer=backupvault.ListBackupsResponse.deserialize, + ) + return self._stubs["list_backups"] + + @property + def fetch_backups_for_resource_type( + self, + ) -> Callable[ + [backupvault.FetchBackupsForResourceTypeRequest], + backupvault.FetchBackupsForResourceTypeResponse, + ]: + r"""Return a callable for the fetch backups for resource + type method over gRPC. + + Fetch Backups for a given resource type. + + Returns: + Callable[[~.FetchBackupsForResourceTypeRequest], + ~.FetchBackupsForResourceTypeResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_backups_for_resource_type" not in self._stubs: + self._stubs["fetch_backups_for_resource_type"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchBackupsForResourceType", + request_serializer=backupvault.FetchBackupsForResourceTypeRequest.serialize, + response_deserializer=backupvault.FetchBackupsForResourceTypeResponse.deserialize, + ) + ) + return self._stubs["fetch_backups_for_resource_type"] + + @property + def get_backup( + self, + ) -> Callable[[backupvault.GetBackupRequest], backupvault.Backup]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a Backup. + + Returns: + Callable[[~.GetBackupRequest], + ~.Backup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup" not in self._stubs: + self._stubs["get_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackup", + request_serializer=backupvault.GetBackupRequest.serialize, + response_deserializer=backupvault.Backup.deserialize, + ) + return self._stubs["get_backup"] + + @property + def update_backup( + self, + ) -> Callable[[backupvault.UpdateBackupRequest], operations_pb2.Operation]: + r"""Return a callable for the update backup method over gRPC. + + Updates the settings of a Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup" not in self._stubs: + self._stubs["update_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackup", + request_serializer=backupvault.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_backup"] + + @property + def delete_backup( + self, + ) -> Callable[[backupvault.DeleteBackupRequest], operations_pb2.Operation]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a Backup. + + Returns: + Callable[[~.DeleteBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup" not in self._stubs: + self._stubs["delete_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackup", + request_serializer=backupvault.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup"] + + @property + def restore_backup( + self, + ) -> Callable[[backupvault.RestoreBackupRequest], operations_pb2.Operation]: + r"""Return a callable for the restore backup method over gRPC. + + Restore from a Backup + + Returns: + Callable[[~.RestoreBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "restore_backup" not in self._stubs: + self._stubs["restore_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/RestoreBackup", + request_serializer=backupvault.RestoreBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["restore_backup"] + + @property + def create_backup_plan( + self, + ) -> Callable[[backupplan.CreateBackupPlanRequest], operations_pb2.Operation]: + r"""Return a callable for the create backup plan method over gRPC. + + Create a BackupPlan + + Returns: + Callable[[~.CreateBackupPlanRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_backup_plan" not in self._stubs: + self._stubs["create_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateBackupPlan", + request_serializer=backupplan.CreateBackupPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_backup_plan"] + + @property + def update_backup_plan( + self, + ) -> Callable[[backupplan.UpdateBackupPlanRequest], operations_pb2.Operation]: + r"""Return a callable for the update backup plan method over gRPC. + + Update a BackupPlan. + + Returns: + Callable[[~.UpdateBackupPlanRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup_plan" not in self._stubs: + self._stubs["update_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackupPlan", + request_serializer=backupplan.UpdateBackupPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_backup_plan"] + + @property + def get_backup_plan( + self, + ) -> Callable[[backupplan.GetBackupPlanRequest], backupplan.BackupPlan]: + r"""Return a callable for the get backup plan method over gRPC. + + Gets details of a single BackupPlan. + + Returns: + Callable[[~.GetBackupPlanRequest], + ~.BackupPlan]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_plan" not in self._stubs: + self._stubs["get_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupPlan", + request_serializer=backupplan.GetBackupPlanRequest.serialize, + response_deserializer=backupplan.BackupPlan.deserialize, + ) + return self._stubs["get_backup_plan"] + + @property + def list_backup_plans( + self, + ) -> Callable[ + [backupplan.ListBackupPlansRequest], backupplan.ListBackupPlansResponse + ]: + r"""Return a callable for the list backup plans method over gRPC. + + Lists BackupPlans in a given project and location. + + Returns: + Callable[[~.ListBackupPlansRequest], + ~.ListBackupPlansResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_plans" not in self._stubs: + self._stubs["list_backup_plans"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupPlans", + request_serializer=backupplan.ListBackupPlansRequest.serialize, + response_deserializer=backupplan.ListBackupPlansResponse.deserialize, + ) + return self._stubs["list_backup_plans"] + + @property + def delete_backup_plan( + self, + ) -> Callable[[backupplan.DeleteBackupPlanRequest], operations_pb2.Operation]: + r"""Return a callable for the delete backup plan method over gRPC. + + Deletes a single BackupPlan. + + Returns: + Callable[[~.DeleteBackupPlanRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup_plan" not in self._stubs: + self._stubs["delete_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackupPlan", + request_serializer=backupplan.DeleteBackupPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup_plan"] + + @property + def get_backup_plan_revision( + self, + ) -> Callable[ + [backupplan.GetBackupPlanRevisionRequest], backupplan.BackupPlanRevision + ]: + r"""Return a callable for the get backup plan revision method over gRPC. + + Gets details of a single BackupPlanRevision. + + Returns: + Callable[[~.GetBackupPlanRevisionRequest], + ~.BackupPlanRevision]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_plan_revision" not in self._stubs: + self._stubs["get_backup_plan_revision"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupPlanRevision", + request_serializer=backupplan.GetBackupPlanRevisionRequest.serialize, + response_deserializer=backupplan.BackupPlanRevision.deserialize, + ) + return self._stubs["get_backup_plan_revision"] + + @property + def list_backup_plan_revisions( + self, + ) -> Callable[ + [backupplan.ListBackupPlanRevisionsRequest], + backupplan.ListBackupPlanRevisionsResponse, + ]: + r"""Return a callable for the list backup plan revisions method over gRPC. + + Lists BackupPlanRevisions in a given project and + location. + + Returns: + Callable[[~.ListBackupPlanRevisionsRequest], + ~.ListBackupPlanRevisionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_plan_revisions" not in self._stubs: + self._stubs["list_backup_plan_revisions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupPlanRevisions", + request_serializer=backupplan.ListBackupPlanRevisionsRequest.serialize, + response_deserializer=backupplan.ListBackupPlanRevisionsResponse.deserialize, + ) + ) + return self._stubs["list_backup_plan_revisions"] + + @property + def create_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.CreateBackupPlanAssociationRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create backup plan association method over gRPC. + + Create a BackupPlanAssociation + + Returns: + Callable[[~.CreateBackupPlanAssociationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_backup_plan_association" not in self._stubs: + self._stubs["create_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateBackupPlanAssociation", + request_serializer=backupplanassociation.CreateBackupPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_backup_plan_association"] + + @property + def update_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.UpdateBackupPlanAssociationRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the update backup plan association method over gRPC. + + Update a BackupPlanAssociation. + + Returns: + Callable[[~.UpdateBackupPlanAssociationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup_plan_association" not in self._stubs: + self._stubs["update_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackupPlanAssociation", + request_serializer=backupplanassociation.UpdateBackupPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_backup_plan_association"] + + @property + def get_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.GetBackupPlanAssociationRequest], + backupplanassociation.BackupPlanAssociation, + ]: + r"""Return a callable for the get backup plan association method over gRPC. + + Gets details of a single BackupPlanAssociation. + + Returns: + Callable[[~.GetBackupPlanAssociationRequest], + ~.BackupPlanAssociation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_plan_association" not in self._stubs: + self._stubs["get_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupPlanAssociation", + request_serializer=backupplanassociation.GetBackupPlanAssociationRequest.serialize, + response_deserializer=backupplanassociation.BackupPlanAssociation.deserialize, + ) + ) + return self._stubs["get_backup_plan_association"] + + @property + def list_backup_plan_associations( + self, + ) -> Callable[ + [backupplanassociation.ListBackupPlanAssociationsRequest], + backupplanassociation.ListBackupPlanAssociationsResponse, + ]: + r"""Return a callable for the list backup plan associations method over gRPC. + + Lists BackupPlanAssociations in a given project and + location. + + Returns: + Callable[[~.ListBackupPlanAssociationsRequest], + ~.ListBackupPlanAssociationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_plan_associations" not in self._stubs: + self._stubs["list_backup_plan_associations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupPlanAssociations", + request_serializer=backupplanassociation.ListBackupPlanAssociationsRequest.serialize, + response_deserializer=backupplanassociation.ListBackupPlanAssociationsResponse.deserialize, + ) + ) + return self._stubs["list_backup_plan_associations"] + + @property + def fetch_backup_plan_associations_for_resource_type( + self, + ) -> Callable[ + [backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest], + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + ]: + r"""Return a callable for the fetch backup plan associations + for resource type method over gRPC. + + List BackupPlanAssociations for a given resource + type. + + Returns: + Callable[[~.FetchBackupPlanAssociationsForResourceTypeRequest], + ~.FetchBackupPlanAssociationsForResourceTypeResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_backup_plan_associations_for_resource_type" not in self._stubs: + self._stubs["fetch_backup_plan_associations_for_resource_type"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchBackupPlanAssociationsForResourceType", + request_serializer=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest.serialize, + response_deserializer=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.deserialize, + ) + ) + return self._stubs["fetch_backup_plan_associations_for_resource_type"] + + @property + def delete_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.DeleteBackupPlanAssociationRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete backup plan association method over gRPC. + + Deletes a single BackupPlanAssociation. + + Returns: + Callable[[~.DeleteBackupPlanAssociationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup_plan_association" not in self._stubs: + self._stubs["delete_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackupPlanAssociation", + request_serializer=backupplanassociation.DeleteBackupPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_backup_plan_association"] + + @property + def trigger_backup( + self, + ) -> Callable[ + [backupplanassociation.TriggerBackupRequest], operations_pb2.Operation + ]: + r"""Return a callable for the trigger backup method over gRPC. + + Triggers a new Backup. + + Returns: + Callable[[~.TriggerBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "trigger_backup" not in self._stubs: + self._stubs["trigger_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/TriggerBackup", + request_serializer=backupplanassociation.TriggerBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["trigger_backup"] + + @property + def get_data_source_reference( + self, + ) -> Callable[ + [datasourcereference.GetDataSourceReferenceRequest], + datasourcereference.DataSourceReference, + ]: + r"""Return a callable for the get data source reference method over gRPC. + + Gets details of a single DataSourceReference. + + Returns: + Callable[[~.GetDataSourceReferenceRequest], + ~.DataSourceReference]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_data_source_reference" not in self._stubs: + self._stubs["get_data_source_reference"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetDataSourceReference", + request_serializer=datasourcereference.GetDataSourceReferenceRequest.serialize, + response_deserializer=datasourcereference.DataSourceReference.deserialize, + ) + return self._stubs["get_data_source_reference"] + + @property + def list_data_source_references( + self, + ) -> Callable[ + [datasourcereference.ListDataSourceReferencesRequest], + datasourcereference.ListDataSourceReferencesResponse, + ]: + r"""Return a callable for the list data source references method over gRPC. + + Lists DataSourceReferences for a given project and + location. + + Returns: + Callable[[~.ListDataSourceReferencesRequest], + ~.ListDataSourceReferencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_data_source_references" not in self._stubs: + self._stubs["list_data_source_references"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListDataSourceReferences", + request_serializer=datasourcereference.ListDataSourceReferencesRequest.serialize, + response_deserializer=datasourcereference.ListDataSourceReferencesResponse.deserialize, + ) + ) + return self._stubs["list_data_source_references"] + + @property + def fetch_data_source_references_for_resource_type( + self, + ) -> Callable[ + [datasourcereference.FetchDataSourceReferencesForResourceTypeRequest], + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + ]: + r"""Return a callable for the fetch data source references + for resource type method over gRPC. + + Fetch DataSourceReferences for a given project, + location and resource type. + + Returns: + Callable[[~.FetchDataSourceReferencesForResourceTypeRequest], + ~.FetchDataSourceReferencesForResourceTypeResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_data_source_references_for_resource_type" not in self._stubs: + self._stubs["fetch_data_source_references_for_resource_type"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchDataSourceReferencesForResourceType", + request_serializer=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest.serialize, + response_deserializer=datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.deserialize, + ) + ) + return self._stubs["fetch_data_source_references_for_resource_type"] + + @property + def initialize_service( + self, + ) -> Callable[[backupdr.InitializeServiceRequest], operations_pb2.Operation]: + r"""Return a callable for the initialize service method over gRPC. + + Initializes the service related config for a project. + + Returns: + Callable[[~.InitializeServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "initialize_service" not in self._stubs: + self._stubs["initialize_service"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/InitializeService", + request_serializer=backupdr.InitializeServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["initialize_service"] + + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create auto protection policy method over gRPC. + + Creates a new AutoProtectionPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy" not in self._stubs: + self._stubs["create_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.CreateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy"] + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + ]: + r"""Return a callable for the list auto protection policies method over gRPC. + + Lists AutoProtectionPolicies for a given project and + location. + + Returns: + Callable[[~.ListAutoProtectionPoliciesRequest], + ~.ListAutoProtectionPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_auto_protection_policies" not in self._stubs: + self._stubs["list_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListAutoProtectionPolicies", + request_serializer=autoprotectionpolicy.ListAutoProtectionPoliciesRequest.serialize, + response_deserializer=autoprotectionpolicy.ListAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policies"] + + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + autoprotectionpolicy.AutoProtectionPolicy, + ]: + r"""Return a callable for the get auto protection policy method over gRPC. + + Gets details of a single AutoProtectionPolicy. + + Returns: + Callable[[~.GetAutoProtectionPolicyRequest], + ~.AutoProtectionPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_auto_protection_policy" not in self._stubs: + self._stubs["get_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.GetAutoProtectionPolicyRequest.serialize, + response_deserializer=autoprotectionpolicy.AutoProtectionPolicy.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy"] + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the update auto protection policy method over gRPC. + + Updates the parameters of a single + AutoProtectionPolicy. + + Returns: + Callable[[~.UpdateAutoProtectionPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_auto_protection_policy" not in self._stubs: + self._stubs["update_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_auto_protection_policy"] + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete auto protection policy method over gRPC. + + Deletes a single AutoProtectionPolicy. + + Returns: + Callable[[~.DeleteAutoProtectionPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_auto_protection_policy" not in self._stubs: + self._stubs["delete_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_auto_protection_policy"] + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create auto protection policy + binding method over gRPC. + + Creates a new AutoProtectionPolicyBinding in a given + project and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy_binding" not in self._stubs: + self._stubs["create_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy_binding"] + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + ]: + r"""Return a callable for the get auto protection policy + binding method over gRPC. + + Returns the auto protection policy binding read from + the CCFE tables. + + Returns: + Callable[[~.GetAutoProtectionPolicyBindingRequest], + ~.AutoProtectionPolicyBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_auto_protection_policy_binding" not in self._stubs: + self._stubs["get_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=autoprotectionpolicybinding.AutoProtectionPolicyBinding.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy_binding"] + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + ]: + r"""Return a callable for the list auto protection policy + bindings method over gRPC. + + Returns the auto protection policy bindings read from + the CCFE tables. + + Returns: + Callable[[~.ListAutoProtectionPolicyBindingsRequest], + ~.ListAutoProtectionPolicyBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_auto_protection_policy_bindings" not in self._stubs: + self._stubs["list_auto_protection_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListAutoProtectionPolicyBindings", + request_serializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest.serialize, + response_deserializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policy_bindings"] + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + ]: + r"""Return a callable for the list applied auto protection + policies method over gRPC. + + Lists AppliedAutoProtectionPolicies in a given + project and location. + + Returns: + Callable[[~.ListAppliedAutoProtectionPoliciesRequest], + ~.ListAppliedAutoProtectionPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_applied_auto_protection_policies" not in self._stubs: + self._stubs["list_applied_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListAppliedAutoProtectionPolicies", + request_serializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest.serialize, + response_deserializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_applied_auto_protection_policies"] + + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the initiate delete auto + protection policy binding method over gRPC. + + InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + Returns: + Callable[[~.InitiateDeleteAutoProtectionPolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "initiate_delete_auto_protection_policy_binding" not in self._stubs: + self._stubs["initiate_delete_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/InitiateDeleteAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["initiate_delete_auto_protection_policy_binding"] + + @property + def get_binding_matching_resource( + self, + ) -> Callable[ + [bindingmatchingresource.GetBindingMatchingResourceRequest], + bindingmatchingresource.BindingMatchingResource, + ]: + r"""Return a callable for the get binding matching resource method over gRPC. + + Gets details of a single Binding Matching Resource. + + Returns: + Callable[[~.GetBindingMatchingResourceRequest], + ~.BindingMatchingResource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_binding_matching_resource" not in self._stubs: + self._stubs["get_binding_matching_resource"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBindingMatchingResource", + request_serializer=bindingmatchingresource.GetBindingMatchingResourceRequest.serialize, + response_deserializer=bindingmatchingresource.BindingMatchingResource.deserialize, + ) + ) + return self._stubs["get_binding_matching_resource"] + + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + bindingmatchingresource.ListBindingMatchingResourcesResponse, + ]: + r"""Return a callable for the list binding matching + resources method over gRPC. + + Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + Returns: + Callable[[~.ListBindingMatchingResourcesRequest], + ~.ListBindingMatchingResourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_binding_matching_resources" not in self._stubs: + self._stubs["list_binding_matching_resources"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBindingMatchingResources", + request_serializer=bindingmatchingresource.ListBindingMatchingResourcesRequest.serialize, + response_deserializer=bindingmatchingresource.ListBindingMatchingResourcesResponse.deserialize, + ) + ) + return self._stubs["list_binding_matching_resources"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("BackupDRGrpcTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc_asyncio.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc_asyncio.py new file mode 100644 index 000000000000..cede18e6c601 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc_asyncio.py @@ -0,0 +1,2447 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + bindingmatchingresource, + datasourcereference, +) + +from .base import DEFAULT_CLIENT_INFO, BackupDRTransport +from .grpc import BackupDRGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BackupDRGrpcAsyncIOTransport(BackupDRTransport): + """gRPC AsyncIO backend transport for BackupDR. + + The BackupDR Service + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_management_servers( + self, + ) -> Callable[ + [backupdr.ListManagementServersRequest], + Awaitable[backupdr.ListManagementServersResponse], + ]: + r"""Return a callable for the list management servers method over gRPC. + + Lists ManagementServers in a given project and + location. + + Returns: + Callable[[~.ListManagementServersRequest], + Awaitable[~.ListManagementServersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_management_servers" not in self._stubs: + self._stubs["list_management_servers"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListManagementServers", + request_serializer=backupdr.ListManagementServersRequest.serialize, + response_deserializer=backupdr.ListManagementServersResponse.deserialize, + ) + return self._stubs["list_management_servers"] + + @property + def get_management_server( + self, + ) -> Callable[ + [backupdr.GetManagementServerRequest], Awaitable[backupdr.ManagementServer] + ]: + r"""Return a callable for the get management server method over gRPC. + + Gets details of a single ManagementServer. + + Returns: + Callable[[~.GetManagementServerRequest], + Awaitable[~.ManagementServer]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_management_server" not in self._stubs: + self._stubs["get_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetManagementServer", + request_serializer=backupdr.GetManagementServerRequest.serialize, + response_deserializer=backupdr.ManagementServer.deserialize, + ) + return self._stubs["get_management_server"] + + @property + def create_management_server( + self, + ) -> Callable[ + [backupdr.CreateManagementServerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create management server method over gRPC. + + Creates a new ManagementServer in a given project and + location. + + Returns: + Callable[[~.CreateManagementServerRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_management_server" not in self._stubs: + self._stubs["create_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateManagementServer", + request_serializer=backupdr.CreateManagementServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_management_server"] + + @property + def delete_management_server( + self, + ) -> Callable[ + [backupdr.DeleteManagementServerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete management server method over gRPC. + + Deletes a single ManagementServer. + + Returns: + Callable[[~.DeleteManagementServerRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_management_server" not in self._stubs: + self._stubs["delete_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteManagementServer", + request_serializer=backupdr.DeleteManagementServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_management_server"] + + @property + def create_backup_vault( + self, + ) -> Callable[ + [backupvault.CreateBackupVaultRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create backup vault method over gRPC. + + Creates a new BackupVault in a given project and + location. + + Returns: + Callable[[~.CreateBackupVaultRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_backup_vault" not in self._stubs: + self._stubs["create_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateBackupVault", + request_serializer=backupvault.CreateBackupVaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_backup_vault"] + + @property + def list_backup_vaults( + self, + ) -> Callable[ + [backupvault.ListBackupVaultsRequest], + Awaitable[backupvault.ListBackupVaultsResponse], + ]: + r"""Return a callable for the list backup vaults method over gRPC. + + Lists BackupVaults in a given project and location. + + Returns: + Callable[[~.ListBackupVaultsRequest], + Awaitable[~.ListBackupVaultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_vaults" not in self._stubs: + self._stubs["list_backup_vaults"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupVaults", + request_serializer=backupvault.ListBackupVaultsRequest.serialize, + response_deserializer=backupvault.ListBackupVaultsResponse.deserialize, + ) + return self._stubs["list_backup_vaults"] + + @property + def fetch_usable_backup_vaults( + self, + ) -> Callable[ + [backupvault.FetchUsableBackupVaultsRequest], + Awaitable[backupvault.FetchUsableBackupVaultsResponse], + ]: + r"""Return a callable for the fetch usable backup vaults method over gRPC. + + FetchUsableBackupVaults lists usable BackupVaults in + a given project and location. Usable BackupVault are the + ones that user has backupdr.backupVaults.get permission. + + Returns: + Callable[[~.FetchUsableBackupVaultsRequest], + Awaitable[~.FetchUsableBackupVaultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_usable_backup_vaults" not in self._stubs: + self._stubs["fetch_usable_backup_vaults"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchUsableBackupVaults", + request_serializer=backupvault.FetchUsableBackupVaultsRequest.serialize, + response_deserializer=backupvault.FetchUsableBackupVaultsResponse.deserialize, + ) + ) + return self._stubs["fetch_usable_backup_vaults"] + + @property + def get_backup_vault( + self, + ) -> Callable[ + [backupvault.GetBackupVaultRequest], Awaitable[backupvault.BackupVault] + ]: + r"""Return a callable for the get backup vault method over gRPC. + + Gets details of a BackupVault. + + Returns: + Callable[[~.GetBackupVaultRequest], + Awaitable[~.BackupVault]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_vault" not in self._stubs: + self._stubs["get_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupVault", + request_serializer=backupvault.GetBackupVaultRequest.serialize, + response_deserializer=backupvault.BackupVault.deserialize, + ) + return self._stubs["get_backup_vault"] + + @property + def update_backup_vault( + self, + ) -> Callable[ + [backupvault.UpdateBackupVaultRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update backup vault method over gRPC. + + Updates the settings of a BackupVault. + + Returns: + Callable[[~.UpdateBackupVaultRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup_vault" not in self._stubs: + self._stubs["update_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackupVault", + request_serializer=backupvault.UpdateBackupVaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_backup_vault"] + + @property + def delete_backup_vault( + self, + ) -> Callable[ + [backupvault.DeleteBackupVaultRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete backup vault method over gRPC. + + Deletes a BackupVault. + + Returns: + Callable[[~.DeleteBackupVaultRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup_vault" not in self._stubs: + self._stubs["delete_backup_vault"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackupVault", + request_serializer=backupvault.DeleteBackupVaultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup_vault"] + + @property + def list_data_sources( + self, + ) -> Callable[ + [backupvault.ListDataSourcesRequest], + Awaitable[backupvault.ListDataSourcesResponse], + ]: + r"""Return a callable for the list data sources method over gRPC. + + Lists DataSources in a given project and location. + + Returns: + Callable[[~.ListDataSourcesRequest], + Awaitable[~.ListDataSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_data_sources" not in self._stubs: + self._stubs["list_data_sources"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListDataSources", + request_serializer=backupvault.ListDataSourcesRequest.serialize, + response_deserializer=backupvault.ListDataSourcesResponse.deserialize, + ) + return self._stubs["list_data_sources"] + + @property + def get_data_source( + self, + ) -> Callable[ + [backupvault.GetDataSourceRequest], Awaitable[backupvault.DataSource] + ]: + r"""Return a callable for the get data source method over gRPC. + + Gets details of a DataSource. + + Returns: + Callable[[~.GetDataSourceRequest], + Awaitable[~.DataSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_data_source" not in self._stubs: + self._stubs["get_data_source"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetDataSource", + request_serializer=backupvault.GetDataSourceRequest.serialize, + response_deserializer=backupvault.DataSource.deserialize, + ) + return self._stubs["get_data_source"] + + @property + def update_data_source( + self, + ) -> Callable[ + [backupvault.UpdateDataSourceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update data source method over gRPC. + + Updates the settings of a DataSource. + + Returns: + Callable[[~.UpdateDataSourceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_data_source" not in self._stubs: + self._stubs["update_data_source"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateDataSource", + request_serializer=backupvault.UpdateDataSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_data_source"] + + @property + def list_backups( + self, + ) -> Callable[ + [backupvault.ListBackupsRequest], Awaitable[backupvault.ListBackupsResponse] + ]: + r"""Return a callable for the list backups method over gRPC. + + Lists Backups in a given project and location. + + Returns: + Callable[[~.ListBackupsRequest], + Awaitable[~.ListBackupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backups" not in self._stubs: + self._stubs["list_backups"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackups", + request_serializer=backupvault.ListBackupsRequest.serialize, + response_deserializer=backupvault.ListBackupsResponse.deserialize, + ) + return self._stubs["list_backups"] + + @property + def fetch_backups_for_resource_type( + self, + ) -> Callable[ + [backupvault.FetchBackupsForResourceTypeRequest], + Awaitable[backupvault.FetchBackupsForResourceTypeResponse], + ]: + r"""Return a callable for the fetch backups for resource + type method over gRPC. + + Fetch Backups for a given resource type. + + Returns: + Callable[[~.FetchBackupsForResourceTypeRequest], + Awaitable[~.FetchBackupsForResourceTypeResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_backups_for_resource_type" not in self._stubs: + self._stubs["fetch_backups_for_resource_type"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchBackupsForResourceType", + request_serializer=backupvault.FetchBackupsForResourceTypeRequest.serialize, + response_deserializer=backupvault.FetchBackupsForResourceTypeResponse.deserialize, + ) + ) + return self._stubs["fetch_backups_for_resource_type"] + + @property + def get_backup( + self, + ) -> Callable[[backupvault.GetBackupRequest], Awaitable[backupvault.Backup]]: + r"""Return a callable for the get backup method over gRPC. + + Gets details of a Backup. + + Returns: + Callable[[~.GetBackupRequest], + Awaitable[~.Backup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup" not in self._stubs: + self._stubs["get_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackup", + request_serializer=backupvault.GetBackupRequest.serialize, + response_deserializer=backupvault.Backup.deserialize, + ) + return self._stubs["get_backup"] + + @property + def update_backup( + self, + ) -> Callable[ + [backupvault.UpdateBackupRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update backup method over gRPC. + + Updates the settings of a Backup. + + Returns: + Callable[[~.UpdateBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup" not in self._stubs: + self._stubs["update_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackup", + request_serializer=backupvault.UpdateBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_backup"] + + @property + def delete_backup( + self, + ) -> Callable[ + [backupvault.DeleteBackupRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a Backup. + + Returns: + Callable[[~.DeleteBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup" not in self._stubs: + self._stubs["delete_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackup", + request_serializer=backupvault.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup"] + + @property + def restore_backup( + self, + ) -> Callable[ + [backupvault.RestoreBackupRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the restore backup method over gRPC. + + Restore from a Backup + + Returns: + Callable[[~.RestoreBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "restore_backup" not in self._stubs: + self._stubs["restore_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/RestoreBackup", + request_serializer=backupvault.RestoreBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["restore_backup"] + + @property + def create_backup_plan( + self, + ) -> Callable[ + [backupplan.CreateBackupPlanRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create backup plan method over gRPC. + + Create a BackupPlan + + Returns: + Callable[[~.CreateBackupPlanRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_backup_plan" not in self._stubs: + self._stubs["create_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateBackupPlan", + request_serializer=backupplan.CreateBackupPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_backup_plan"] + + @property + def update_backup_plan( + self, + ) -> Callable[ + [backupplan.UpdateBackupPlanRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update backup plan method over gRPC. + + Update a BackupPlan. + + Returns: + Callable[[~.UpdateBackupPlanRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup_plan" not in self._stubs: + self._stubs["update_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackupPlan", + request_serializer=backupplan.UpdateBackupPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_backup_plan"] + + @property + def get_backup_plan( + self, + ) -> Callable[[backupplan.GetBackupPlanRequest], Awaitable[backupplan.BackupPlan]]: + r"""Return a callable for the get backup plan method over gRPC. + + Gets details of a single BackupPlan. + + Returns: + Callable[[~.GetBackupPlanRequest], + Awaitable[~.BackupPlan]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_plan" not in self._stubs: + self._stubs["get_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupPlan", + request_serializer=backupplan.GetBackupPlanRequest.serialize, + response_deserializer=backupplan.BackupPlan.deserialize, + ) + return self._stubs["get_backup_plan"] + + @property + def list_backup_plans( + self, + ) -> Callable[ + [backupplan.ListBackupPlansRequest], + Awaitable[backupplan.ListBackupPlansResponse], + ]: + r"""Return a callable for the list backup plans method over gRPC. + + Lists BackupPlans in a given project and location. + + Returns: + Callable[[~.ListBackupPlansRequest], + Awaitable[~.ListBackupPlansResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_plans" not in self._stubs: + self._stubs["list_backup_plans"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupPlans", + request_serializer=backupplan.ListBackupPlansRequest.serialize, + response_deserializer=backupplan.ListBackupPlansResponse.deserialize, + ) + return self._stubs["list_backup_plans"] + + @property + def delete_backup_plan( + self, + ) -> Callable[ + [backupplan.DeleteBackupPlanRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete backup plan method over gRPC. + + Deletes a single BackupPlan. + + Returns: + Callable[[~.DeleteBackupPlanRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup_plan" not in self._stubs: + self._stubs["delete_backup_plan"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackupPlan", + request_serializer=backupplan.DeleteBackupPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup_plan"] + + @property + def get_backup_plan_revision( + self, + ) -> Callable[ + [backupplan.GetBackupPlanRevisionRequest], + Awaitable[backupplan.BackupPlanRevision], + ]: + r"""Return a callable for the get backup plan revision method over gRPC. + + Gets details of a single BackupPlanRevision. + + Returns: + Callable[[~.GetBackupPlanRevisionRequest], + Awaitable[~.BackupPlanRevision]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_plan_revision" not in self._stubs: + self._stubs["get_backup_plan_revision"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupPlanRevision", + request_serializer=backupplan.GetBackupPlanRevisionRequest.serialize, + response_deserializer=backupplan.BackupPlanRevision.deserialize, + ) + return self._stubs["get_backup_plan_revision"] + + @property + def list_backup_plan_revisions( + self, + ) -> Callable[ + [backupplan.ListBackupPlanRevisionsRequest], + Awaitable[backupplan.ListBackupPlanRevisionsResponse], + ]: + r"""Return a callable for the list backup plan revisions method over gRPC. + + Lists BackupPlanRevisions in a given project and + location. + + Returns: + Callable[[~.ListBackupPlanRevisionsRequest], + Awaitable[~.ListBackupPlanRevisionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_plan_revisions" not in self._stubs: + self._stubs["list_backup_plan_revisions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupPlanRevisions", + request_serializer=backupplan.ListBackupPlanRevisionsRequest.serialize, + response_deserializer=backupplan.ListBackupPlanRevisionsResponse.deserialize, + ) + ) + return self._stubs["list_backup_plan_revisions"] + + @property + def create_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.CreateBackupPlanAssociationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create backup plan association method over gRPC. + + Create a BackupPlanAssociation + + Returns: + Callable[[~.CreateBackupPlanAssociationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_backup_plan_association" not in self._stubs: + self._stubs["create_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateBackupPlanAssociation", + request_serializer=backupplanassociation.CreateBackupPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_backup_plan_association"] + + @property + def update_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.UpdateBackupPlanAssociationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update backup plan association method over gRPC. + + Update a BackupPlanAssociation. + + Returns: + Callable[[~.UpdateBackupPlanAssociationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_backup_plan_association" not in self._stubs: + self._stubs["update_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateBackupPlanAssociation", + request_serializer=backupplanassociation.UpdateBackupPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_backup_plan_association"] + + @property + def get_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.GetBackupPlanAssociationRequest], + Awaitable[backupplanassociation.BackupPlanAssociation], + ]: + r"""Return a callable for the get backup plan association method over gRPC. + + Gets details of a single BackupPlanAssociation. + + Returns: + Callable[[~.GetBackupPlanAssociationRequest], + Awaitable[~.BackupPlanAssociation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_plan_association" not in self._stubs: + self._stubs["get_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBackupPlanAssociation", + request_serializer=backupplanassociation.GetBackupPlanAssociationRequest.serialize, + response_deserializer=backupplanassociation.BackupPlanAssociation.deserialize, + ) + ) + return self._stubs["get_backup_plan_association"] + + @property + def list_backup_plan_associations( + self, + ) -> Callable[ + [backupplanassociation.ListBackupPlanAssociationsRequest], + Awaitable[backupplanassociation.ListBackupPlanAssociationsResponse], + ]: + r"""Return a callable for the list backup plan associations method over gRPC. + + Lists BackupPlanAssociations in a given project and + location. + + Returns: + Callable[[~.ListBackupPlanAssociationsRequest], + Awaitable[~.ListBackupPlanAssociationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_plan_associations" not in self._stubs: + self._stubs["list_backup_plan_associations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBackupPlanAssociations", + request_serializer=backupplanassociation.ListBackupPlanAssociationsRequest.serialize, + response_deserializer=backupplanassociation.ListBackupPlanAssociationsResponse.deserialize, + ) + ) + return self._stubs["list_backup_plan_associations"] + + @property + def fetch_backup_plan_associations_for_resource_type( + self, + ) -> Callable[ + [backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest], + Awaitable[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse + ], + ]: + r"""Return a callable for the fetch backup plan associations + for resource type method over gRPC. + + List BackupPlanAssociations for a given resource + type. + + Returns: + Callable[[~.FetchBackupPlanAssociationsForResourceTypeRequest], + Awaitable[~.FetchBackupPlanAssociationsForResourceTypeResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_backup_plan_associations_for_resource_type" not in self._stubs: + self._stubs["fetch_backup_plan_associations_for_resource_type"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchBackupPlanAssociationsForResourceType", + request_serializer=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest.serialize, + response_deserializer=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.deserialize, + ) + ) + return self._stubs["fetch_backup_plan_associations_for_resource_type"] + + @property + def delete_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.DeleteBackupPlanAssociationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete backup plan association method over gRPC. + + Deletes a single BackupPlanAssociation. + + Returns: + Callable[[~.DeleteBackupPlanAssociationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup_plan_association" not in self._stubs: + self._stubs["delete_backup_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteBackupPlanAssociation", + request_serializer=backupplanassociation.DeleteBackupPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_backup_plan_association"] + + @property + def trigger_backup( + self, + ) -> Callable[ + [backupplanassociation.TriggerBackupRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the trigger backup method over gRPC. + + Triggers a new Backup. + + Returns: + Callable[[~.TriggerBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "trigger_backup" not in self._stubs: + self._stubs["trigger_backup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/TriggerBackup", + request_serializer=backupplanassociation.TriggerBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["trigger_backup"] + + @property + def get_data_source_reference( + self, + ) -> Callable[ + [datasourcereference.GetDataSourceReferenceRequest], + Awaitable[datasourcereference.DataSourceReference], + ]: + r"""Return a callable for the get data source reference method over gRPC. + + Gets details of a single DataSourceReference. + + Returns: + Callable[[~.GetDataSourceReferenceRequest], + Awaitable[~.DataSourceReference]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_data_source_reference" not in self._stubs: + self._stubs["get_data_source_reference"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetDataSourceReference", + request_serializer=datasourcereference.GetDataSourceReferenceRequest.serialize, + response_deserializer=datasourcereference.DataSourceReference.deserialize, + ) + return self._stubs["get_data_source_reference"] + + @property + def list_data_source_references( + self, + ) -> Callable[ + [datasourcereference.ListDataSourceReferencesRequest], + Awaitable[datasourcereference.ListDataSourceReferencesResponse], + ]: + r"""Return a callable for the list data source references method over gRPC. + + Lists DataSourceReferences for a given project and + location. + + Returns: + Callable[[~.ListDataSourceReferencesRequest], + Awaitable[~.ListDataSourceReferencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_data_source_references" not in self._stubs: + self._stubs["list_data_source_references"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListDataSourceReferences", + request_serializer=datasourcereference.ListDataSourceReferencesRequest.serialize, + response_deserializer=datasourcereference.ListDataSourceReferencesResponse.deserialize, + ) + ) + return self._stubs["list_data_source_references"] + + @property + def fetch_data_source_references_for_resource_type( + self, + ) -> Callable[ + [datasourcereference.FetchDataSourceReferencesForResourceTypeRequest], + Awaitable[datasourcereference.FetchDataSourceReferencesForResourceTypeResponse], + ]: + r"""Return a callable for the fetch data source references + for resource type method over gRPC. + + Fetch DataSourceReferences for a given project, + location and resource type. + + Returns: + Callable[[~.FetchDataSourceReferencesForResourceTypeRequest], + Awaitable[~.FetchDataSourceReferencesForResourceTypeResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_data_source_references_for_resource_type" not in self._stubs: + self._stubs["fetch_data_source_references_for_resource_type"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/FetchDataSourceReferencesForResourceType", + request_serializer=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest.serialize, + response_deserializer=datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.deserialize, + ) + ) + return self._stubs["fetch_data_source_references_for_resource_type"] + + @property + def initialize_service( + self, + ) -> Callable[ + [backupdr.InitializeServiceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the initialize service method over gRPC. + + Initializes the service related config for a project. + + Returns: + Callable[[~.InitializeServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "initialize_service" not in self._stubs: + self._stubs["initialize_service"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/InitializeService", + request_serializer=backupdr.InitializeServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["initialize_service"] + + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create auto protection policy method over gRPC. + + Creates a new AutoProtectionPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy" not in self._stubs: + self._stubs["create_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.CreateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy"] + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + Awaitable[autoprotectionpolicy.ListAutoProtectionPoliciesResponse], + ]: + r"""Return a callable for the list auto protection policies method over gRPC. + + Lists AutoProtectionPolicies for a given project and + location. + + Returns: + Callable[[~.ListAutoProtectionPoliciesRequest], + Awaitable[~.ListAutoProtectionPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_auto_protection_policies" not in self._stubs: + self._stubs["list_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListAutoProtectionPolicies", + request_serializer=autoprotectionpolicy.ListAutoProtectionPoliciesRequest.serialize, + response_deserializer=autoprotectionpolicy.ListAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policies"] + + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + Awaitable[autoprotectionpolicy.AutoProtectionPolicy], + ]: + r"""Return a callable for the get auto protection policy method over gRPC. + + Gets details of a single AutoProtectionPolicy. + + Returns: + Callable[[~.GetAutoProtectionPolicyRequest], + Awaitable[~.AutoProtectionPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_auto_protection_policy" not in self._stubs: + self._stubs["get_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.GetAutoProtectionPolicyRequest.serialize, + response_deserializer=autoprotectionpolicy.AutoProtectionPolicy.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy"] + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update auto protection policy method over gRPC. + + Updates the parameters of a single + AutoProtectionPolicy. + + Returns: + Callable[[~.UpdateAutoProtectionPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_auto_protection_policy" not in self._stubs: + self._stubs["update_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_auto_protection_policy"] + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete auto protection policy method over gRPC. + + Deletes a single AutoProtectionPolicy. + + Returns: + Callable[[~.DeleteAutoProtectionPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_auto_protection_policy" not in self._stubs: + self._stubs["delete_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_auto_protection_policy"] + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create auto protection policy + binding method over gRPC. + + Creates a new AutoProtectionPolicyBinding in a given + project and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy_binding" not in self._stubs: + self._stubs["create_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy_binding"] + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + Awaitable[autoprotectionpolicybinding.AutoProtectionPolicyBinding], + ]: + r"""Return a callable for the get auto protection policy + binding method over gRPC. + + Returns the auto protection policy binding read from + the CCFE tables. + + Returns: + Callable[[~.GetAutoProtectionPolicyBindingRequest], + Awaitable[~.AutoProtectionPolicyBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_auto_protection_policy_binding" not in self._stubs: + self._stubs["get_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=autoprotectionpolicybinding.AutoProtectionPolicyBinding.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy_binding"] + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + Awaitable[autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse], + ]: + r"""Return a callable for the list auto protection policy + bindings method over gRPC. + + Returns the auto protection policy bindings read from + the CCFE tables. + + Returns: + Callable[[~.ListAutoProtectionPolicyBindingsRequest], + Awaitable[~.ListAutoProtectionPolicyBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_auto_protection_policy_bindings" not in self._stubs: + self._stubs["list_auto_protection_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListAutoProtectionPolicyBindings", + request_serializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest.serialize, + response_deserializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policy_bindings"] + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + Awaitable[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + ]: + r"""Return a callable for the list applied auto protection + policies method over gRPC. + + Lists AppliedAutoProtectionPolicies in a given + project and location. + + Returns: + Callable[[~.ListAppliedAutoProtectionPoliciesRequest], + Awaitable[~.ListAppliedAutoProtectionPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_applied_auto_protection_policies" not in self._stubs: + self._stubs["list_applied_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListAppliedAutoProtectionPolicies", + request_serializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest.serialize, + response_deserializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_applied_auto_protection_policies"] + + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the initiate delete auto + protection policy binding method over gRPC. + + InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + Returns: + Callable[[~.InitiateDeleteAutoProtectionPolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "initiate_delete_auto_protection_policy_binding" not in self._stubs: + self._stubs["initiate_delete_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/InitiateDeleteAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["initiate_delete_auto_protection_policy_binding"] + + @property + def get_binding_matching_resource( + self, + ) -> Callable[ + [bindingmatchingresource.GetBindingMatchingResourceRequest], + Awaitable[bindingmatchingresource.BindingMatchingResource], + ]: + r"""Return a callable for the get binding matching resource method over gRPC. + + Gets details of a single Binding Matching Resource. + + Returns: + Callable[[~.GetBindingMatchingResourceRequest], + Awaitable[~.BindingMatchingResource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_binding_matching_resource" not in self._stubs: + self._stubs["get_binding_matching_resource"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetBindingMatchingResource", + request_serializer=bindingmatchingresource.GetBindingMatchingResourceRequest.serialize, + response_deserializer=bindingmatchingresource.BindingMatchingResource.deserialize, + ) + ) + return self._stubs["get_binding_matching_resource"] + + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + Awaitable[bindingmatchingresource.ListBindingMatchingResourcesResponse], + ]: + r"""Return a callable for the list binding matching + resources method over gRPC. + + Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + Returns: + Callable[[~.ListBindingMatchingResourcesRequest], + Awaitable[~.ListBindingMatchingResourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_binding_matching_resources" not in self._stubs: + self._stubs["list_binding_matching_resources"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListBindingMatchingResources", + request_serializer=bindingmatchingresource.ListBindingMatchingResourcesRequest.serialize, + response_deserializer=bindingmatchingresource.ListBindingMatchingResourcesResponse.deserialize, + ) + ) + return self._stubs["list_binding_matching_resources"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_management_servers: self._wrap_method( + self.list_management_servers, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_management_server: self._wrap_method( + self.get_management_server, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_management_server: self._wrap_method( + self.create_management_server, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_management_server: self._wrap_method( + self.delete_management_server, + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup_vault: self._wrap_method( + self.create_backup_vault, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_backup_vaults: self._wrap_method( + self.list_backup_vaults, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_usable_backup_vaults: self._wrap_method( + self.fetch_usable_backup_vaults, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_backup_vault: self._wrap_method( + self.get_backup_vault, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_backup_vault: self._wrap_method( + self.update_backup_vault, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup_vault: self._wrap_method( + self.delete_backup_vault, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_data_sources: self._wrap_method( + self.list_data_sources, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_data_source: self._wrap_method( + self.get_data_source, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_data_source: self._wrap_method( + self.update_data_source, + default_timeout=60.0, + client_info=client_info, + ), + self.list_backups: self._wrap_method( + self.list_backups, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_backups_for_resource_type: self._wrap_method( + self.fetch_backups_for_resource_type, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: self._wrap_method( + self.get_backup, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_backup: self._wrap_method( + self.update_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup: self._wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.restore_backup: self._wrap_method( + self.restore_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup_plan: self._wrap_method( + self.create_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.update_backup_plan: self._wrap_method( + self.update_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan: self._wrap_method( + self.get_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plans: self._wrap_method( + self.list_backup_plans, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup_plan: self._wrap_method( + self.delete_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan_revision: self._wrap_method( + self.get_backup_plan_revision, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plan_revisions: self._wrap_method( + self.list_backup_plan_revisions, + default_timeout=None, + client_info=client_info, + ), + self.create_backup_plan_association: self._wrap_method( + self.create_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.update_backup_plan_association: self._wrap_method( + self.update_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan_association: self._wrap_method( + self.get_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plan_associations: self._wrap_method( + self.list_backup_plan_associations, + default_timeout=None, + client_info=client_info, + ), + self.fetch_backup_plan_associations_for_resource_type: self._wrap_method( + self.fetch_backup_plan_associations_for_resource_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup_plan_association: self._wrap_method( + self.delete_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.trigger_backup: self._wrap_method( + self.trigger_backup, + default_timeout=None, + client_info=client_info, + ), + self.get_data_source_reference: self._wrap_method( + self.get_data_source_reference, + default_timeout=None, + client_info=client_info, + ), + self.list_data_source_references: self._wrap_method( + self.list_data_source_references, + default_timeout=None, + client_info=client_info, + ), + self.fetch_data_source_references_for_resource_type: self._wrap_method( + self.fetch_data_source_references_for_resource_type, + default_timeout=None, + client_info=client_info, + ), + self.initialize_service: self._wrap_method( + self.initialize_service, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_auto_protection_policy: self._wrap_method( + self.create_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_auto_protection_policies: self._wrap_method( + self.list_auto_protection_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_auto_protection_policy: self._wrap_method( + self.get_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_auto_protection_policy: self._wrap_method( + self.update_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_auto_protection_policy: self._wrap_method( + self.delete_auto_protection_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_auto_protection_policy_binding: self._wrap_method( + self.create_auto_protection_policy_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_auto_protection_policy_binding: self._wrap_method( + self.get_auto_protection_policy_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_auto_protection_policy_bindings: self._wrap_method( + self.list_auto_protection_policy_bindings, + default_timeout=None, + client_info=client_info, + ), + self.list_applied_auto_protection_policies: self._wrap_method( + self.list_applied_auto_protection_policies, + default_timeout=None, + client_info=client_info, + ), + self.initiate_delete_auto_protection_policy_binding: self._wrap_method( + self.initiate_delete_auto_protection_policy_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_binding_matching_resource: self._wrap_method( + self.get_binding_matching_resource, + default_timeout=None, + client_info=client_info, + ), + self.list_binding_matching_resources: self._wrap_method( + self.list_binding_matching_resources, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("BackupDRGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest.py new file mode 100644 index 000000000000..2b3221f80cac --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest.py @@ -0,0 +1,12503 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.backupdr_v1beta._compat import transcode_request +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + bindingmatchingresource, + datasourcereference, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseBackupDRRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class BackupDRRestInterceptor: + """Interceptor for BackupDR. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the BackupDRRestTransport. + + .. code-block:: python + class MyCustomBackupDRInterceptor(BackupDRRestInterceptor): + def pre_create_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_auto_protection_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_auto_protection_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_auto_protection_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_backup_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_backup_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_backup_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_backup_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_backup_vault(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_backup_vault(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_management_server(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_management_server(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_auto_protection_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup_vault(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup_vault(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_management_server(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_management_server(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_backup_plan_associations_for_resource_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_backup_plan_associations_for_resource_type(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_backups_for_resource_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_backups_for_resource_type(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_data_source_references_for_resource_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_data_source_references_for_resource_type(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_usable_backup_vaults(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_usable_backup_vaults(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_auto_protection_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_auto_protection_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_auto_protection_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup_plan_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup_plan_revision(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup_vault(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup_vault(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_binding_matching_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_binding_matching_resource(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_source_reference(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_source_reference(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_management_server(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_management_server(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_initialize_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_initialize_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_initiate_delete_auto_protection_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_initiate_delete_auto_protection_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_applied_auto_protection_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_applied_auto_protection_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_auto_protection_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_auto_protection_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_auto_protection_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_auto_protection_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backup_plan_associations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backup_plan_associations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backup_plan_revisions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backup_plan_revisions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backup_plans(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backup_plans(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backup_vaults(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backup_vaults(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_binding_matching_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_binding_matching_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_source_references(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_source_references(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_management_servers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_management_servers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_trigger_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_trigger_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_auto_protection_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_backup_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_backup_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_backup_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_backup_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_backup_vault(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_backup_vault(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BackupDRRestTransport(interceptor=MyCustomBackupDRInterceptor()) + client = BackupDRClient(transport=transport) + + + """ + + def pre_create_auto_protection_policy( + self, + request: autoprotectionpolicy.CreateAutoProtectionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_auto_protection_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_auto_protection_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_auto_protection_policy + + DEPRECATED. Please use the `post_create_auto_protection_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_auto_protection_policy` interceptor runs + before the `post_create_auto_protection_policy_with_metadata` interceptor. + """ + return response + + def post_create_auto_protection_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_auto_protection_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_create_auto_protection_policy` interceptor. + When both interceptors are used, this `post_create_auto_protection_policy_with_metadata` interceptor runs after the + `post_create_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_create_auto_protection_policy` will be passed to + `post_create_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_create_auto_protection_policy_binding( + self, + request: autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_auto_protection_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_auto_protection_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_auto_protection_policy_binding + + DEPRECATED. Please use the `post_create_auto_protection_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_auto_protection_policy_binding` interceptor runs + before the `post_create_auto_protection_policy_binding_with_metadata` interceptor. + """ + return response + + def post_create_auto_protection_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_auto_protection_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_auto_protection_policy_binding_with_metadata` + interceptor in new development instead of the `post_create_auto_protection_policy_binding` interceptor. + When both interceptors are used, this `post_create_auto_protection_policy_binding_with_metadata` interceptor runs after the + `post_create_auto_protection_policy_binding` interceptor. The (possibly modified) response returned by + `post_create_auto_protection_policy_binding` will be passed to + `post_create_auto_protection_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_create_backup_plan( + self, + request: backupplan.CreateBackupPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.CreateBackupPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_backup_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_backup_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_backup_plan + + DEPRECATED. Please use the `post_create_backup_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_backup_plan` interceptor runs + before the `post_create_backup_plan_with_metadata` interceptor. + """ + return response + + def post_create_backup_plan_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_backup_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_backup_plan_with_metadata` + interceptor in new development instead of the `post_create_backup_plan` interceptor. + When both interceptors are used, this `post_create_backup_plan_with_metadata` interceptor runs after the + `post_create_backup_plan` interceptor. The (possibly modified) response returned by + `post_create_backup_plan` will be passed to + `post_create_backup_plan_with_metadata`. + """ + return response, metadata + + def pre_create_backup_plan_association( + self, + request: backupplanassociation.CreateBackupPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.CreateBackupPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_backup_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_backup_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_backup_plan_association + + DEPRECATED. Please use the `post_create_backup_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_backup_plan_association` interceptor runs + before the `post_create_backup_plan_association_with_metadata` interceptor. + """ + return response + + def post_create_backup_plan_association_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_backup_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_backup_plan_association_with_metadata` + interceptor in new development instead of the `post_create_backup_plan_association` interceptor. + When both interceptors are used, this `post_create_backup_plan_association_with_metadata` interceptor runs after the + `post_create_backup_plan_association` interceptor. The (possibly modified) response returned by + `post_create_backup_plan_association` will be passed to + `post_create_backup_plan_association_with_metadata`. + """ + return response, metadata + + def pre_create_backup_vault( + self, + request: backupvault.CreateBackupVaultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.CreateBackupVaultRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_backup_vault + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_backup_vault( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_backup_vault + + DEPRECATED. Please use the `post_create_backup_vault_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_backup_vault` interceptor runs + before the `post_create_backup_vault_with_metadata` interceptor. + """ + return response + + def post_create_backup_vault_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_backup_vault + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_backup_vault_with_metadata` + interceptor in new development instead of the `post_create_backup_vault` interceptor. + When both interceptors are used, this `post_create_backup_vault_with_metadata` interceptor runs after the + `post_create_backup_vault` interceptor. The (possibly modified) response returned by + `post_create_backup_vault` will be passed to + `post_create_backup_vault_with_metadata`. + """ + return response, metadata + + def pre_create_management_server( + self, + request: backupdr.CreateManagementServerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupdr.CreateManagementServerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_management_server + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_management_server( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_management_server + + DEPRECATED. Please use the `post_create_management_server_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_management_server` interceptor runs + before the `post_create_management_server_with_metadata` interceptor. + """ + return response + + def post_create_management_server_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_management_server + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_management_server_with_metadata` + interceptor in new development instead of the `post_create_management_server` interceptor. + When both interceptors are used, this `post_create_management_server_with_metadata` interceptor runs after the + `post_create_management_server` interceptor. The (possibly modified) response returned by + `post_create_management_server` will be passed to + `post_create_management_server_with_metadata`. + """ + return response, metadata + + def pre_delete_auto_protection_policy( + self, + request: autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_auto_protection_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_auto_protection_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_auto_protection_policy + + DEPRECATED. Please use the `post_delete_auto_protection_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_auto_protection_policy` interceptor runs + before the `post_delete_auto_protection_policy_with_metadata` interceptor. + """ + return response + + def post_delete_auto_protection_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_auto_protection_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_delete_auto_protection_policy` interceptor. + When both interceptors are used, this `post_delete_auto_protection_policy_with_metadata` interceptor runs after the + `post_delete_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_delete_auto_protection_policy` will be passed to + `post_delete_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_backup( + self, + request: backupvault.DeleteBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.DeleteBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup + + DEPRECATED. Please use the `post_delete_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_backup` interceptor runs + before the `post_delete_backup_with_metadata` interceptor. + """ + return response + + def post_delete_backup_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_backup_with_metadata` + interceptor in new development instead of the `post_delete_backup` interceptor. + When both interceptors are used, this `post_delete_backup_with_metadata` interceptor runs after the + `post_delete_backup` interceptor. The (possibly modified) response returned by + `post_delete_backup` will be passed to + `post_delete_backup_with_metadata`. + """ + return response, metadata + + def pre_delete_backup_plan( + self, + request: backupplan.DeleteBackupPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.DeleteBackupPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_backup_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_backup_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup_plan + + DEPRECATED. Please use the `post_delete_backup_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_backup_plan` interceptor runs + before the `post_delete_backup_plan_with_metadata` interceptor. + """ + return response + + def post_delete_backup_plan_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_backup_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_backup_plan_with_metadata` + interceptor in new development instead of the `post_delete_backup_plan` interceptor. + When both interceptors are used, this `post_delete_backup_plan_with_metadata` interceptor runs after the + `post_delete_backup_plan` interceptor. The (possibly modified) response returned by + `post_delete_backup_plan` will be passed to + `post_delete_backup_plan_with_metadata`. + """ + return response, metadata + + def pre_delete_backup_plan_association( + self, + request: backupplanassociation.DeleteBackupPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.DeleteBackupPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_backup_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_backup_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup_plan_association + + DEPRECATED. Please use the `post_delete_backup_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_backup_plan_association` interceptor runs + before the `post_delete_backup_plan_association_with_metadata` interceptor. + """ + return response + + def post_delete_backup_plan_association_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_backup_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_backup_plan_association_with_metadata` + interceptor in new development instead of the `post_delete_backup_plan_association` interceptor. + When both interceptors are used, this `post_delete_backup_plan_association_with_metadata` interceptor runs after the + `post_delete_backup_plan_association` interceptor. The (possibly modified) response returned by + `post_delete_backup_plan_association` will be passed to + `post_delete_backup_plan_association_with_metadata`. + """ + return response, metadata + + def pre_delete_backup_vault( + self, + request: backupvault.DeleteBackupVaultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.DeleteBackupVaultRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_backup_vault + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_backup_vault( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup_vault + + DEPRECATED. Please use the `post_delete_backup_vault_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_backup_vault` interceptor runs + before the `post_delete_backup_vault_with_metadata` interceptor. + """ + return response + + def post_delete_backup_vault_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_backup_vault + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_backup_vault_with_metadata` + interceptor in new development instead of the `post_delete_backup_vault` interceptor. + When both interceptors are used, this `post_delete_backup_vault_with_metadata` interceptor runs after the + `post_delete_backup_vault` interceptor. The (possibly modified) response returned by + `post_delete_backup_vault` will be passed to + `post_delete_backup_vault_with_metadata`. + """ + return response, metadata + + def pre_delete_management_server( + self, + request: backupdr.DeleteManagementServerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupdr.DeleteManagementServerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_management_server + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_management_server( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_management_server + + DEPRECATED. Please use the `post_delete_management_server_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_management_server` interceptor runs + before the `post_delete_management_server_with_metadata` interceptor. + """ + return response + + def post_delete_management_server_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_management_server + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_management_server_with_metadata` + interceptor in new development instead of the `post_delete_management_server` interceptor. + When both interceptors are used, this `post_delete_management_server_with_metadata` interceptor runs after the + `post_delete_management_server` interceptor. The (possibly modified) response returned by + `post_delete_management_server` will be passed to + `post_delete_management_server_with_metadata`. + """ + return response, metadata + + def pre_fetch_backup_plan_associations_for_resource_type( + self, + request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_backup_plan_associations_for_resource_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_fetch_backup_plan_associations_for_resource_type( + self, + response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + """Post-rpc interceptor for fetch_backup_plan_associations_for_resource_type + + DEPRECATED. Please use the `post_fetch_backup_plan_associations_for_resource_type_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_fetch_backup_plan_associations_for_resource_type` interceptor runs + before the `post_fetch_backup_plan_associations_for_resource_type_with_metadata` interceptor. + """ + return response + + def post_fetch_backup_plan_associations_for_resource_type_with_metadata( + self, + response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_backup_plan_associations_for_resource_type + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_fetch_backup_plan_associations_for_resource_type_with_metadata` + interceptor in new development instead of the `post_fetch_backup_plan_associations_for_resource_type` interceptor. + When both interceptors are used, this `post_fetch_backup_plan_associations_for_resource_type_with_metadata` interceptor runs after the + `post_fetch_backup_plan_associations_for_resource_type` interceptor. The (possibly modified) response returned by + `post_fetch_backup_plan_associations_for_resource_type` will be passed to + `post_fetch_backup_plan_associations_for_resource_type_with_metadata`. + """ + return response, metadata + + def pre_fetch_backups_for_resource_type( + self, + request: backupvault.FetchBackupsForResourceTypeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.FetchBackupsForResourceTypeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_backups_for_resource_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_fetch_backups_for_resource_type( + self, response: backupvault.FetchBackupsForResourceTypeResponse + ) -> backupvault.FetchBackupsForResourceTypeResponse: + """Post-rpc interceptor for fetch_backups_for_resource_type + + DEPRECATED. Please use the `post_fetch_backups_for_resource_type_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_fetch_backups_for_resource_type` interceptor runs + before the `post_fetch_backups_for_resource_type_with_metadata` interceptor. + """ + return response + + def post_fetch_backups_for_resource_type_with_metadata( + self, + response: backupvault.FetchBackupsForResourceTypeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.FetchBackupsForResourceTypeResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_backups_for_resource_type + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_fetch_backups_for_resource_type_with_metadata` + interceptor in new development instead of the `post_fetch_backups_for_resource_type` interceptor. + When both interceptors are used, this `post_fetch_backups_for_resource_type_with_metadata` interceptor runs after the + `post_fetch_backups_for_resource_type` interceptor. The (possibly modified) response returned by + `post_fetch_backups_for_resource_type` will be passed to + `post_fetch_backups_for_resource_type_with_metadata`. + """ + return response, metadata + + def pre_fetch_data_source_references_for_resource_type( + self, + request: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_data_source_references_for_resource_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_fetch_data_source_references_for_resource_type( + self, + response: datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + ) -> datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: + """Post-rpc interceptor for fetch_data_source_references_for_resource_type + + DEPRECATED. Please use the `post_fetch_data_source_references_for_resource_type_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_fetch_data_source_references_for_resource_type` interceptor runs + before the `post_fetch_data_source_references_for_resource_type_with_metadata` interceptor. + """ + return response + + def post_fetch_data_source_references_for_resource_type_with_metadata( + self, + response: datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_data_source_references_for_resource_type + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_fetch_data_source_references_for_resource_type_with_metadata` + interceptor in new development instead of the `post_fetch_data_source_references_for_resource_type` interceptor. + When both interceptors are used, this `post_fetch_data_source_references_for_resource_type_with_metadata` interceptor runs after the + `post_fetch_data_source_references_for_resource_type` interceptor. The (possibly modified) response returned by + `post_fetch_data_source_references_for_resource_type` will be passed to + `post_fetch_data_source_references_for_resource_type_with_metadata`. + """ + return response, metadata + + def pre_fetch_usable_backup_vaults( + self, + request: backupvault.FetchUsableBackupVaultsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.FetchUsableBackupVaultsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_usable_backup_vaults + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_fetch_usable_backup_vaults( + self, response: backupvault.FetchUsableBackupVaultsResponse + ) -> backupvault.FetchUsableBackupVaultsResponse: + """Post-rpc interceptor for fetch_usable_backup_vaults + + DEPRECATED. Please use the `post_fetch_usable_backup_vaults_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_fetch_usable_backup_vaults` interceptor runs + before the `post_fetch_usable_backup_vaults_with_metadata` interceptor. + """ + return response + + def post_fetch_usable_backup_vaults_with_metadata( + self, + response: backupvault.FetchUsableBackupVaultsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.FetchUsableBackupVaultsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_usable_backup_vaults + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_fetch_usable_backup_vaults_with_metadata` + interceptor in new development instead of the `post_fetch_usable_backup_vaults` interceptor. + When both interceptors are used, this `post_fetch_usable_backup_vaults_with_metadata` interceptor runs after the + `post_fetch_usable_backup_vaults` interceptor. The (possibly modified) response returned by + `post_fetch_usable_backup_vaults` will be passed to + `post_fetch_usable_backup_vaults_with_metadata`. + """ + return response, metadata + + def pre_get_auto_protection_policy( + self, + request: autoprotectionpolicy.GetAutoProtectionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.GetAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_auto_protection_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_auto_protection_policy( + self, response: autoprotectionpolicy.AutoProtectionPolicy + ) -> autoprotectionpolicy.AutoProtectionPolicy: + """Post-rpc interceptor for get_auto_protection_policy + + DEPRECATED. Please use the `post_get_auto_protection_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_auto_protection_policy` interceptor runs + before the `post_get_auto_protection_policy_with_metadata` interceptor. + """ + return response + + def post_get_auto_protection_policy_with_metadata( + self, + response: autoprotectionpolicy.AutoProtectionPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.AutoProtectionPolicy, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_auto_protection_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_get_auto_protection_policy` interceptor. + When both interceptors are used, this `post_get_auto_protection_policy_with_metadata` interceptor runs after the + `post_get_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_get_auto_protection_policy` will be passed to + `post_get_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_get_auto_protection_policy_binding( + self, + request: autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_auto_protection_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_auto_protection_policy_binding( + self, response: autoprotectionpolicybinding.AutoProtectionPolicyBinding + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + """Post-rpc interceptor for get_auto_protection_policy_binding + + DEPRECATED. Please use the `post_get_auto_protection_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_auto_protection_policy_binding` interceptor runs + before the `post_get_auto_protection_policy_binding_with_metadata` interceptor. + """ + return response + + def post_get_auto_protection_policy_binding_with_metadata( + self, + response: autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_auto_protection_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_auto_protection_policy_binding_with_metadata` + interceptor in new development instead of the `post_get_auto_protection_policy_binding` interceptor. + When both interceptors are used, this `post_get_auto_protection_policy_binding_with_metadata` interceptor runs after the + `post_get_auto_protection_policy_binding` interceptor. The (possibly modified) response returned by + `post_get_auto_protection_policy_binding` will be passed to + `post_get_auto_protection_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_get_backup( + self, + request: backupvault.GetBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupvault.GetBackupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_backup(self, response: backupvault.Backup) -> backupvault.Backup: + """Post-rpc interceptor for get_backup + + DEPRECATED. Please use the `post_get_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_backup` interceptor runs + before the `post_get_backup_with_metadata` interceptor. + """ + return response + + def post_get_backup_with_metadata( + self, + response: backupvault.Backup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupvault.Backup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_backup_with_metadata` + interceptor in new development instead of the `post_get_backup` interceptor. + When both interceptors are used, this `post_get_backup_with_metadata` interceptor runs after the + `post_get_backup` interceptor. The (possibly modified) response returned by + `post_get_backup` will be passed to + `post_get_backup_with_metadata`. + """ + return response, metadata + + def pre_get_backup_plan( + self, + request: backupplan.GetBackupPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.GetBackupPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_backup_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_backup_plan( + self, response: backupplan.BackupPlan + ) -> backupplan.BackupPlan: + """Post-rpc interceptor for get_backup_plan + + DEPRECATED. Please use the `post_get_backup_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_backup_plan` interceptor runs + before the `post_get_backup_plan_with_metadata` interceptor. + """ + return response + + def post_get_backup_plan_with_metadata( + self, + response: backupplan.BackupPlan, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupplan.BackupPlan, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_backup_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_backup_plan_with_metadata` + interceptor in new development instead of the `post_get_backup_plan` interceptor. + When both interceptors are used, this `post_get_backup_plan_with_metadata` interceptor runs after the + `post_get_backup_plan` interceptor. The (possibly modified) response returned by + `post_get_backup_plan` will be passed to + `post_get_backup_plan_with_metadata`. + """ + return response, metadata + + def pre_get_backup_plan_association( + self, + request: backupplanassociation.GetBackupPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.GetBackupPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_backup_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_backup_plan_association( + self, response: backupplanassociation.BackupPlanAssociation + ) -> backupplanassociation.BackupPlanAssociation: + """Post-rpc interceptor for get_backup_plan_association + + DEPRECATED. Please use the `post_get_backup_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_backup_plan_association` interceptor runs + before the `post_get_backup_plan_association_with_metadata` interceptor. + """ + return response + + def post_get_backup_plan_association_with_metadata( + self, + response: backupplanassociation.BackupPlanAssociation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.BackupPlanAssociation, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_backup_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_backup_plan_association_with_metadata` + interceptor in new development instead of the `post_get_backup_plan_association` interceptor. + When both interceptors are used, this `post_get_backup_plan_association_with_metadata` interceptor runs after the + `post_get_backup_plan_association` interceptor. The (possibly modified) response returned by + `post_get_backup_plan_association` will be passed to + `post_get_backup_plan_association_with_metadata`. + """ + return response, metadata + + def pre_get_backup_plan_revision( + self, + request: backupplan.GetBackupPlanRevisionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.GetBackupPlanRevisionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_backup_plan_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_backup_plan_revision( + self, response: backupplan.BackupPlanRevision + ) -> backupplan.BackupPlanRevision: + """Post-rpc interceptor for get_backup_plan_revision + + DEPRECATED. Please use the `post_get_backup_plan_revision_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_backup_plan_revision` interceptor runs + before the `post_get_backup_plan_revision_with_metadata` interceptor. + """ + return response + + def post_get_backup_plan_revision_with_metadata( + self, + response: backupplan.BackupPlanRevision, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupplan.BackupPlanRevision, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_backup_plan_revision + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_backup_plan_revision_with_metadata` + interceptor in new development instead of the `post_get_backup_plan_revision` interceptor. + When both interceptors are used, this `post_get_backup_plan_revision_with_metadata` interceptor runs after the + `post_get_backup_plan_revision` interceptor. The (possibly modified) response returned by + `post_get_backup_plan_revision` will be passed to + `post_get_backup_plan_revision_with_metadata`. + """ + return response, metadata + + def pre_get_backup_vault( + self, + request: backupvault.GetBackupVaultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.GetBackupVaultRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_backup_vault + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_backup_vault( + self, response: backupvault.BackupVault + ) -> backupvault.BackupVault: + """Post-rpc interceptor for get_backup_vault + + DEPRECATED. Please use the `post_get_backup_vault_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_backup_vault` interceptor runs + before the `post_get_backup_vault_with_metadata` interceptor. + """ + return response + + def post_get_backup_vault_with_metadata( + self, + response: backupvault.BackupVault, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupvault.BackupVault, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_backup_vault + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_backup_vault_with_metadata` + interceptor in new development instead of the `post_get_backup_vault` interceptor. + When both interceptors are used, this `post_get_backup_vault_with_metadata` interceptor runs after the + `post_get_backup_vault` interceptor. The (possibly modified) response returned by + `post_get_backup_vault` will be passed to + `post_get_backup_vault_with_metadata`. + """ + return response, metadata + + def pre_get_binding_matching_resource( + self, + request: bindingmatchingresource.GetBindingMatchingResourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bindingmatchingresource.GetBindingMatchingResourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_binding_matching_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_binding_matching_resource( + self, response: bindingmatchingresource.BindingMatchingResource + ) -> bindingmatchingresource.BindingMatchingResource: + """Post-rpc interceptor for get_binding_matching_resource + + DEPRECATED. Please use the `post_get_binding_matching_resource_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_binding_matching_resource` interceptor runs + before the `post_get_binding_matching_resource_with_metadata` interceptor. + """ + return response + + def post_get_binding_matching_resource_with_metadata( + self, + response: bindingmatchingresource.BindingMatchingResource, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bindingmatchingresource.BindingMatchingResource, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_binding_matching_resource + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_binding_matching_resource_with_metadata` + interceptor in new development instead of the `post_get_binding_matching_resource` interceptor. + When both interceptors are used, this `post_get_binding_matching_resource_with_metadata` interceptor runs after the + `post_get_binding_matching_resource` interceptor. The (possibly modified) response returned by + `post_get_binding_matching_resource` will be passed to + `post_get_binding_matching_resource_with_metadata`. + """ + return response, metadata + + def pre_get_data_source( + self, + request: backupvault.GetDataSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.GetDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_data_source( + self, response: backupvault.DataSource + ) -> backupvault.DataSource: + """Post-rpc interceptor for get_data_source + + DEPRECATED. Please use the `post_get_data_source_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_data_source` interceptor runs + before the `post_get_data_source_with_metadata` interceptor. + """ + return response + + def post_get_data_source_with_metadata( + self, + response: backupvault.DataSource, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupvault.DataSource, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_data_source + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_data_source_with_metadata` + interceptor in new development instead of the `post_get_data_source` interceptor. + When both interceptors are used, this `post_get_data_source_with_metadata` interceptor runs after the + `post_get_data_source` interceptor. The (possibly modified) response returned by + `post_get_data_source` will be passed to + `post_get_data_source_with_metadata`. + """ + return response, metadata + + def pre_get_data_source_reference( + self, + request: datasourcereference.GetDataSourceReferenceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasourcereference.GetDataSourceReferenceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_data_source_reference + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_data_source_reference( + self, response: datasourcereference.DataSourceReference + ) -> datasourcereference.DataSourceReference: + """Post-rpc interceptor for get_data_source_reference + + DEPRECATED. Please use the `post_get_data_source_reference_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_data_source_reference` interceptor runs + before the `post_get_data_source_reference_with_metadata` interceptor. + """ + return response + + def post_get_data_source_reference_with_metadata( + self, + response: datasourcereference.DataSourceReference, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasourcereference.DataSourceReference, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_data_source_reference + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_data_source_reference_with_metadata` + interceptor in new development instead of the `post_get_data_source_reference` interceptor. + When both interceptors are used, this `post_get_data_source_reference_with_metadata` interceptor runs after the + `post_get_data_source_reference` interceptor. The (possibly modified) response returned by + `post_get_data_source_reference` will be passed to + `post_get_data_source_reference_with_metadata`. + """ + return response, metadata + + def pre_get_management_server( + self, + request: backupdr.GetManagementServerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupdr.GetManagementServerRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_management_server + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_management_server( + self, response: backupdr.ManagementServer + ) -> backupdr.ManagementServer: + """Post-rpc interceptor for get_management_server + + DEPRECATED. Please use the `post_get_management_server_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_management_server` interceptor runs + before the `post_get_management_server_with_metadata` interceptor. + """ + return response + + def post_get_management_server_with_metadata( + self, + response: backupdr.ManagementServer, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupdr.ManagementServer, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_management_server + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_management_server_with_metadata` + interceptor in new development instead of the `post_get_management_server` interceptor. + When both interceptors are used, this `post_get_management_server_with_metadata` interceptor runs after the + `post_get_management_server` interceptor. The (possibly modified) response returned by + `post_get_management_server` will be passed to + `post_get_management_server_with_metadata`. + """ + return response, metadata + + def pre_initialize_service( + self, + request: backupdr.InitializeServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupdr.InitializeServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for initialize_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_initialize_service( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for initialize_service + + DEPRECATED. Please use the `post_initialize_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_initialize_service` interceptor runs + before the `post_initialize_service_with_metadata` interceptor. + """ + return response + + def post_initialize_service_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for initialize_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_initialize_service_with_metadata` + interceptor in new development instead of the `post_initialize_service` interceptor. + When both interceptors are used, this `post_initialize_service_with_metadata` interceptor runs after the + `post_initialize_service` interceptor. The (possibly modified) response returned by + `post_initialize_service` will be passed to + `post_initialize_service_with_metadata`. + """ + return response, metadata + + def pre_initiate_delete_auto_protection_policy_binding( + self, + request: autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for initiate_delete_auto_protection_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_initiate_delete_auto_protection_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for initiate_delete_auto_protection_policy_binding + + DEPRECATED. Please use the `post_initiate_delete_auto_protection_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_initiate_delete_auto_protection_policy_binding` interceptor runs + before the `post_initiate_delete_auto_protection_policy_binding_with_metadata` interceptor. + """ + return response + + def post_initiate_delete_auto_protection_policy_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for initiate_delete_auto_protection_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_initiate_delete_auto_protection_policy_binding_with_metadata` + interceptor in new development instead of the `post_initiate_delete_auto_protection_policy_binding` interceptor. + When both interceptors are used, this `post_initiate_delete_auto_protection_policy_binding_with_metadata` interceptor runs after the + `post_initiate_delete_auto_protection_policy_binding` interceptor. The (possibly modified) response returned by + `post_initiate_delete_auto_protection_policy_binding` will be passed to + `post_initiate_delete_auto_protection_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_list_applied_auto_protection_policies( + self, + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_applied_auto_protection_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_applied_auto_protection_policies( + self, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + ) -> appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + """Post-rpc interceptor for list_applied_auto_protection_policies + + DEPRECATED. Please use the `post_list_applied_auto_protection_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_applied_auto_protection_policies` interceptor runs + before the `post_list_applied_auto_protection_policies_with_metadata` interceptor. + """ + return response + + def post_list_applied_auto_protection_policies_with_metadata( + self, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_applied_auto_protection_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_applied_auto_protection_policies_with_metadata` + interceptor in new development instead of the `post_list_applied_auto_protection_policies` interceptor. + When both interceptors are used, this `post_list_applied_auto_protection_policies_with_metadata` interceptor runs after the + `post_list_applied_auto_protection_policies` interceptor. The (possibly modified) response returned by + `post_list_applied_auto_protection_policies` will be passed to + `post_list_applied_auto_protection_policies_with_metadata`. + """ + return response, metadata + + def pre_list_auto_protection_policies( + self, + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_auto_protection_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_auto_protection_policies( + self, response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse + ) -> autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + """Post-rpc interceptor for list_auto_protection_policies + + DEPRECATED. Please use the `post_list_auto_protection_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_auto_protection_policies` interceptor runs + before the `post_list_auto_protection_policies_with_metadata` interceptor. + """ + return response + + def post_list_auto_protection_policies_with_metadata( + self, + response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_auto_protection_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_auto_protection_policies_with_metadata` + interceptor in new development instead of the `post_list_auto_protection_policies` interceptor. + When both interceptors are used, this `post_list_auto_protection_policies_with_metadata` interceptor runs after the + `post_list_auto_protection_policies` interceptor. The (possibly modified) response returned by + `post_list_auto_protection_policies` will be passed to + `post_list_auto_protection_policies_with_metadata`. + """ + return response, metadata + + def pre_list_auto_protection_policy_bindings( + self, + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_auto_protection_policy_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_auto_protection_policy_bindings( + self, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + ) -> autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + """Post-rpc interceptor for list_auto_protection_policy_bindings + + DEPRECATED. Please use the `post_list_auto_protection_policy_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_auto_protection_policy_bindings` interceptor runs + before the `post_list_auto_protection_policy_bindings_with_metadata` interceptor. + """ + return response + + def post_list_auto_protection_policy_bindings_with_metadata( + self, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_auto_protection_policy_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_auto_protection_policy_bindings_with_metadata` + interceptor in new development instead of the `post_list_auto_protection_policy_bindings` interceptor. + When both interceptors are used, this `post_list_auto_protection_policy_bindings_with_metadata` interceptor runs after the + `post_list_auto_protection_policy_bindings` interceptor. The (possibly modified) response returned by + `post_list_auto_protection_policy_bindings` will be passed to + `post_list_auto_protection_policy_bindings_with_metadata`. + """ + return response, metadata + + def pre_list_backup_plan_associations( + self, + request: backupplanassociation.ListBackupPlanAssociationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.ListBackupPlanAssociationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_backup_plan_associations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_backup_plan_associations( + self, response: backupplanassociation.ListBackupPlanAssociationsResponse + ) -> backupplanassociation.ListBackupPlanAssociationsResponse: + """Post-rpc interceptor for list_backup_plan_associations + + DEPRECATED. Please use the `post_list_backup_plan_associations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_backup_plan_associations` interceptor runs + before the `post_list_backup_plan_associations_with_metadata` interceptor. + """ + return response + + def post_list_backup_plan_associations_with_metadata( + self, + response: backupplanassociation.ListBackupPlanAssociationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.ListBackupPlanAssociationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_backup_plan_associations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_backup_plan_associations_with_metadata` + interceptor in new development instead of the `post_list_backup_plan_associations` interceptor. + When both interceptors are used, this `post_list_backup_plan_associations_with_metadata` interceptor runs after the + `post_list_backup_plan_associations` interceptor. The (possibly modified) response returned by + `post_list_backup_plan_associations` will be passed to + `post_list_backup_plan_associations_with_metadata`. + """ + return response, metadata + + def pre_list_backup_plan_revisions( + self, + request: backupplan.ListBackupPlanRevisionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.ListBackupPlanRevisionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_backup_plan_revisions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_backup_plan_revisions( + self, response: backupplan.ListBackupPlanRevisionsResponse + ) -> backupplan.ListBackupPlanRevisionsResponse: + """Post-rpc interceptor for list_backup_plan_revisions + + DEPRECATED. Please use the `post_list_backup_plan_revisions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_backup_plan_revisions` interceptor runs + before the `post_list_backup_plan_revisions_with_metadata` interceptor. + """ + return response + + def post_list_backup_plan_revisions_with_metadata( + self, + response: backupplan.ListBackupPlanRevisionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.ListBackupPlanRevisionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_backup_plan_revisions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_backup_plan_revisions_with_metadata` + interceptor in new development instead of the `post_list_backup_plan_revisions` interceptor. + When both interceptors are used, this `post_list_backup_plan_revisions_with_metadata` interceptor runs after the + `post_list_backup_plan_revisions` interceptor. The (possibly modified) response returned by + `post_list_backup_plan_revisions` will be passed to + `post_list_backup_plan_revisions_with_metadata`. + """ + return response, metadata + + def pre_list_backup_plans( + self, + request: backupplan.ListBackupPlansRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.ListBackupPlansRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_backup_plans + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_backup_plans( + self, response: backupplan.ListBackupPlansResponse + ) -> backupplan.ListBackupPlansResponse: + """Post-rpc interceptor for list_backup_plans + + DEPRECATED. Please use the `post_list_backup_plans_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_backup_plans` interceptor runs + before the `post_list_backup_plans_with_metadata` interceptor. + """ + return response + + def post_list_backup_plans_with_metadata( + self, + response: backupplan.ListBackupPlansResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.ListBackupPlansResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_backup_plans + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_backup_plans_with_metadata` + interceptor in new development instead of the `post_list_backup_plans` interceptor. + When both interceptors are used, this `post_list_backup_plans_with_metadata` interceptor runs after the + `post_list_backup_plans` interceptor. The (possibly modified) response returned by + `post_list_backup_plans` will be passed to + `post_list_backup_plans_with_metadata`. + """ + return response, metadata + + def pre_list_backups( + self, + request: backupvault.ListBackupsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupvault.ListBackupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_backups + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_backups( + self, response: backupvault.ListBackupsResponse + ) -> backupvault.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + DEPRECATED. Please use the `post_list_backups_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_backups` interceptor runs + before the `post_list_backups_with_metadata` interceptor. + """ + return response + + def post_list_backups_with_metadata( + self, + response: backupvault.ListBackupsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.ListBackupsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_backups + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_backups_with_metadata` + interceptor in new development instead of the `post_list_backups` interceptor. + When both interceptors are used, this `post_list_backups_with_metadata` interceptor runs after the + `post_list_backups` interceptor. The (possibly modified) response returned by + `post_list_backups` will be passed to + `post_list_backups_with_metadata`. + """ + return response, metadata + + def pre_list_backup_vaults( + self, + request: backupvault.ListBackupVaultsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.ListBackupVaultsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_backup_vaults + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_backup_vaults( + self, response: backupvault.ListBackupVaultsResponse + ) -> backupvault.ListBackupVaultsResponse: + """Post-rpc interceptor for list_backup_vaults + + DEPRECATED. Please use the `post_list_backup_vaults_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_backup_vaults` interceptor runs + before the `post_list_backup_vaults_with_metadata` interceptor. + """ + return response + + def post_list_backup_vaults_with_metadata( + self, + response: backupvault.ListBackupVaultsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.ListBackupVaultsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_backup_vaults + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_backup_vaults_with_metadata` + interceptor in new development instead of the `post_list_backup_vaults` interceptor. + When both interceptors are used, this `post_list_backup_vaults_with_metadata` interceptor runs after the + `post_list_backup_vaults` interceptor. The (possibly modified) response returned by + `post_list_backup_vaults` will be passed to + `post_list_backup_vaults_with_metadata`. + """ + return response, metadata + + def pre_list_binding_matching_resources( + self, + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bindingmatchingresource.ListBindingMatchingResourcesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_binding_matching_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_binding_matching_resources( + self, response: bindingmatchingresource.ListBindingMatchingResourcesResponse + ) -> bindingmatchingresource.ListBindingMatchingResourcesResponse: + """Post-rpc interceptor for list_binding_matching_resources + + DEPRECATED. Please use the `post_list_binding_matching_resources_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_binding_matching_resources` interceptor runs + before the `post_list_binding_matching_resources_with_metadata` interceptor. + """ + return response + + def post_list_binding_matching_resources_with_metadata( + self, + response: bindingmatchingresource.ListBindingMatchingResourcesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bindingmatchingresource.ListBindingMatchingResourcesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_binding_matching_resources + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_binding_matching_resources_with_metadata` + interceptor in new development instead of the `post_list_binding_matching_resources` interceptor. + When both interceptors are used, this `post_list_binding_matching_resources_with_metadata` interceptor runs after the + `post_list_binding_matching_resources` interceptor. The (possibly modified) response returned by + `post_list_binding_matching_resources` will be passed to + `post_list_binding_matching_resources_with_metadata`. + """ + return response, metadata + + def pre_list_data_source_references( + self, + request: datasourcereference.ListDataSourceReferencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasourcereference.ListDataSourceReferencesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_data_source_references + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_data_source_references( + self, response: datasourcereference.ListDataSourceReferencesResponse + ) -> datasourcereference.ListDataSourceReferencesResponse: + """Post-rpc interceptor for list_data_source_references + + DEPRECATED. Please use the `post_list_data_source_references_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_data_source_references` interceptor runs + before the `post_list_data_source_references_with_metadata` interceptor. + """ + return response + + def post_list_data_source_references_with_metadata( + self, + response: datasourcereference.ListDataSourceReferencesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datasourcereference.ListDataSourceReferencesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_data_source_references + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_data_source_references_with_metadata` + interceptor in new development instead of the `post_list_data_source_references` interceptor. + When both interceptors are used, this `post_list_data_source_references_with_metadata` interceptor runs after the + `post_list_data_source_references` interceptor. The (possibly modified) response returned by + `post_list_data_source_references` will be passed to + `post_list_data_source_references_with_metadata`. + """ + return response, metadata + + def pre_list_data_sources( + self, + request: backupvault.ListDataSourcesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.ListDataSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_data_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_data_sources( + self, response: backupvault.ListDataSourcesResponse + ) -> backupvault.ListDataSourcesResponse: + """Post-rpc interceptor for list_data_sources + + DEPRECATED. Please use the `post_list_data_sources_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_data_sources` interceptor runs + before the `post_list_data_sources_with_metadata` interceptor. + """ + return response + + def post_list_data_sources_with_metadata( + self, + response: backupvault.ListDataSourcesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.ListDataSourcesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_data_sources + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_data_sources_with_metadata` + interceptor in new development instead of the `post_list_data_sources` interceptor. + When both interceptors are used, this `post_list_data_sources_with_metadata` interceptor runs after the + `post_list_data_sources` interceptor. The (possibly modified) response returned by + `post_list_data_sources` will be passed to + `post_list_data_sources_with_metadata`. + """ + return response, metadata + + def pre_list_management_servers( + self, + request: backupdr.ListManagementServersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupdr.ListManagementServersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_management_servers + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_management_servers( + self, response: backupdr.ListManagementServersResponse + ) -> backupdr.ListManagementServersResponse: + """Post-rpc interceptor for list_management_servers + + DEPRECATED. Please use the `post_list_management_servers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_management_servers` interceptor runs + before the `post_list_management_servers_with_metadata` interceptor. + """ + return response + + def post_list_management_servers_with_metadata( + self, + response: backupdr.ListManagementServersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupdr.ListManagementServersResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_management_servers + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_management_servers_with_metadata` + interceptor in new development instead of the `post_list_management_servers` interceptor. + When both interceptors are used, this `post_list_management_servers_with_metadata` interceptor runs after the + `post_list_management_servers` interceptor. The (possibly modified) response returned by + `post_list_management_servers` will be passed to + `post_list_management_servers_with_metadata`. + """ + return response, metadata + + def pre_restore_backup( + self, + request: backupvault.RestoreBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.RestoreBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for restore_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_restore_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_backup + + DEPRECATED. Please use the `post_restore_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_restore_backup` interceptor runs + before the `post_restore_backup_with_metadata` interceptor. + """ + return response + + def post_restore_backup_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for restore_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_restore_backup_with_metadata` + interceptor in new development instead of the `post_restore_backup` interceptor. + When both interceptors are used, this `post_restore_backup_with_metadata` interceptor runs after the + `post_restore_backup` interceptor. The (possibly modified) response returned by + `post_restore_backup` will be passed to + `post_restore_backup_with_metadata`. + """ + return response, metadata + + def pre_trigger_backup( + self, + request: backupplanassociation.TriggerBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.TriggerBackupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for trigger_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_trigger_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for trigger_backup + + DEPRECATED. Please use the `post_trigger_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_trigger_backup` interceptor runs + before the `post_trigger_backup_with_metadata` interceptor. + """ + return response + + def post_trigger_backup_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for trigger_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_trigger_backup_with_metadata` + interceptor in new development instead of the `post_trigger_backup` interceptor. + When both interceptors are used, this `post_trigger_backup_with_metadata` interceptor runs after the + `post_trigger_backup` interceptor. The (possibly modified) response returned by + `post_trigger_backup` will be passed to + `post_trigger_backup_with_metadata`. + """ + return response, metadata + + def pre_update_auto_protection_policy( + self, + request: autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_auto_protection_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_auto_protection_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_auto_protection_policy + + DEPRECATED. Please use the `post_update_auto_protection_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_auto_protection_policy` interceptor runs + before the `post_update_auto_protection_policy_with_metadata` interceptor. + """ + return response + + def post_update_auto_protection_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_auto_protection_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_update_auto_protection_policy` interceptor. + When both interceptors are used, this `post_update_auto_protection_policy_with_metadata` interceptor runs after the + `post_update_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_update_auto_protection_policy` will be passed to + `post_update_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_update_backup( + self, + request: backupvault.UpdateBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.UpdateBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup + + DEPRECATED. Please use the `post_update_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup` interceptor runs + before the `post_update_backup_with_metadata` interceptor. + """ + return response + + def post_update_backup_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_with_metadata` + interceptor in new development instead of the `post_update_backup` interceptor. + When both interceptors are used, this `post_update_backup_with_metadata` interceptor runs after the + `post_update_backup` interceptor. The (possibly modified) response returned by + `post_update_backup` will be passed to + `post_update_backup_with_metadata`. + """ + return response, metadata + + def pre_update_backup_plan( + self, + request: backupplan.UpdateBackupPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.UpdateBackupPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_backup_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup_plan + + DEPRECATED. Please use the `post_update_backup_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup_plan` interceptor runs + before the `post_update_backup_plan_with_metadata` interceptor. + """ + return response + + def post_update_backup_plan_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_backup_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_plan_with_metadata` + interceptor in new development instead of the `post_update_backup_plan` interceptor. + When both interceptors are used, this `post_update_backup_plan_with_metadata` interceptor runs after the + `post_update_backup_plan` interceptor. The (possibly modified) response returned by + `post_update_backup_plan` will be passed to + `post_update_backup_plan_with_metadata`. + """ + return response, metadata + + def pre_update_backup_plan_association( + self, + request: backupplanassociation.UpdateBackupPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.UpdateBackupPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_backup_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup_plan_association + + DEPRECATED. Please use the `post_update_backup_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup_plan_association` interceptor runs + before the `post_update_backup_plan_association_with_metadata` interceptor. + """ + return response + + def post_update_backup_plan_association_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_backup_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_plan_association_with_metadata` + interceptor in new development instead of the `post_update_backup_plan_association` interceptor. + When both interceptors are used, this `post_update_backup_plan_association_with_metadata` interceptor runs after the + `post_update_backup_plan_association` interceptor. The (possibly modified) response returned by + `post_update_backup_plan_association` will be passed to + `post_update_backup_plan_association_with_metadata`. + """ + return response, metadata + + def pre_update_backup_vault( + self, + request: backupvault.UpdateBackupVaultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.UpdateBackupVaultRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_backup_vault + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup_vault( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup_vault + + DEPRECATED. Please use the `post_update_backup_vault_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup_vault` interceptor runs + before the `post_update_backup_vault_with_metadata` interceptor. + """ + return response + + def post_update_backup_vault_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_backup_vault + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_vault_with_metadata` + interceptor in new development instead of the `post_update_backup_vault` interceptor. + When both interceptors are used, this `post_update_backup_vault_with_metadata` interceptor runs after the + `post_update_backup_vault` interceptor. The (possibly modified) response returned by + `post_update_backup_vault` will be passed to + `post_update_backup_vault_with_metadata`. + """ + return response, metadata + + def pre_update_data_source( + self, + request: backupvault.UpdateDataSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.UpdateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_data_source( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_data_source + + DEPRECATED. Please use the `post_update_data_source_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_data_source` interceptor runs + before the `post_update_data_source_with_metadata` interceptor. + """ + return response + + def post_update_data_source_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_data_source + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_data_source_with_metadata` + interceptor in new development instead of the `post_update_data_source` interceptor. + When both interceptors are used, this `post_update_data_source_with_metadata` interceptor runs after the + `post_update_data_source` interceptor. The (possibly modified) response returned by + `post_update_data_source` will be passed to + `post_update_data_source_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BackupDRRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BackupDRRestInterceptor + + +class BackupDRRestTransport(_BaseBackupDRRestTransport): + """REST backend synchronous transport for BackupDR. + + The BackupDR Service + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[BackupDRRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[BackupDRRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or BackupDRRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicy, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateAutoProtectionPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: autoprotectionpolicy.CreateAutoProtectionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create auto protection + policy method over HTTP. + + Args: + request (~.autoprotectionpolicy.CreateAutoProtectionPolicyRequest): + The request object. Request message for creating an + AutoProtectionPolicy. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_create_auto_protection_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicy, + "_BaseCreateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateAutoProtectionPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateAutoProtectionPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateAutoProtectionPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_auto_protection_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_auto_protection_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_auto_protection_policy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateAutoProtectionPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicyBinding, + BackupDRRestStub, + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateAutoProtectionPolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create auto protection + policy binding method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest): + The request object. Request message for creating an + AutoProtectionPolicyBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicyBinding._get_http_options() + request, metadata = ( + self._interceptor.pre_create_auto_protection_policy_binding( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicyBinding, + "_BaseCreateAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateAutoProtectionPolicyBinding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateAutoProtectionPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._CreateAutoProtectionPolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_auto_protection_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_auto_protection_policy_binding_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_auto_protection_policy_binding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateAutoProtectionPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateBackupPlan( + _BaseBackupDRRestTransport._BaseCreateBackupPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateBackupPlan") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupplan.CreateBackupPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create backup plan method over HTTP. + + Args: + request (~.backupplan.CreateBackupPlanRequest): + The request object. The request message for creating a ``BackupPlan``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseCreateBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_create_backup_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateBackupPlan, + "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateBackupPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateBackupPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateBackupPlan._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_backup_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_backup_plan_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_backup_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateBackupPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateBackupPlanAssociation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupplanassociation.CreateBackupPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create backup plan + association method over HTTP. + + Args: + request (~.backupplanassociation.CreateBackupPlanAssociationRequest): + The request object. Request message for creating a backup + plan. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_create_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation, + "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateBackupPlanAssociation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_backup_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_backup_plan_association_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateBackupVault( + _BaseBackupDRRestTransport._BaseCreateBackupVault, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateBackupVault") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupvault.CreateBackupVaultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create backup vault method over HTTP. + + Args: + request (~.backupvault.CreateBackupVaultRequest): + The request object. Message for creating a BackupVault. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseCreateBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_create_backup_vault( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateBackupVault, + "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateBackupVault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateBackupVault", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateBackupVault._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_backup_vault(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_backup_vault_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_backup_vault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateBackupVault", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateManagementServer( + _BaseBackupDRRestTransport._BaseCreateManagementServer, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateManagementServer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupdr.CreateManagementServerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create management server method over HTTP. + + Args: + request (~.backupdr.CreateManagementServerRequest): + The request object. Request message for creating a + management server instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseCreateManagementServer._get_http_options() + request, metadata = self._interceptor.pre_create_management_server( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateManagementServer, + "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateManagementServer", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateManagementServer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateManagementServer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_management_server(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_management_server_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_management_server", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CreateManagementServer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteAutoProtectionPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete auto protection + policy method over HTTP. + + Args: + request (~.autoprotectionpolicy.DeleteAutoProtectionPolicyRequest): + The request object. Request message for deleting an + AutoProtectionPolicy. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_delete_auto_protection_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, + "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteAutoProtectionPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteAutoProtectionPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteAutoProtectionPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_auto_protection_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_auto_protection_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_auto_protection_policy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteAutoProtectionPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackup(_BaseBackupDRRestTransport._BaseDeleteBackup, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteBackup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.DeleteBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete backup method over HTTP. + + Args: + request (~.backupvault.DeleteBackupRequest): + The request object. Message for deleting a Backup. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseDeleteBackup._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackup, + "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteBackup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackupPlan( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteBackupPlan") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplan.DeleteBackupPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete backup plan method over HTTP. + + Args: + request (~.backupplan.DeleteBackupPlanRequest): + The request object. The request message for deleting a ``BackupPlan``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan, + "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackupPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteBackupPlan._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_backup_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_backup_plan_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackupPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteBackupPlanAssociation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplanassociation.DeleteBackupPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete backup plan + association method over HTTP. + + Args: + request (~.backupplanassociation.DeleteBackupPlanAssociationRequest): + The request object. Request message for deleting a backup + plan association. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_delete_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, + "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteBackupPlanAssociation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_backup_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_backup_plan_association_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackupVault( + _BaseBackupDRRestTransport._BaseDeleteBackupVault, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteBackupVault") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.DeleteBackupVaultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete backup vault method over HTTP. + + Args: + request (~.backupvault.DeleteBackupVaultRequest): + The request object. Message for deleting a BackupVault. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseDeleteBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup_vault( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackupVault, + "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupVault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackupVault", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteBackupVault._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_backup_vault(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_backup_vault_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_vault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteBackupVault", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteManagementServer( + _BaseBackupDRRestTransport._BaseDeleteManagementServer, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteManagementServer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupdr.DeleteManagementServerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete management server method over HTTP. + + Args: + request (~.backupdr.DeleteManagementServerRequest): + The request object. Request message for deleting a + management server instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseDeleteManagementServer._get_http_options() + request, metadata = self._interceptor.pre_delete_management_server( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteManagementServer, + "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteManagementServer", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteManagementServer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteManagementServer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_management_server(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_management_server_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_management_server", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteManagementServer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchBackupPlanAssociationsForResourceType( + _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.FetchBackupPlanAssociationsForResourceType" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + r"""Call the fetch backup plan + associations for resource type method over HTTP. + + Args: + request (~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest): + The request object. Request for the + FetchBackupPlanAssociationsForResourceType + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + Response for the + FetchBackupPlanAssociationsForResourceType + method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_backup_plan_associations_for_resource_type( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, + "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchBackupPlanAssociationsForResourceType", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchBackupPlanAssociationsForResourceType", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchBackupPlanAssociationsForResourceType._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + pb_resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = ( + self._interceptor.post_fetch_backup_plan_associations_for_resource_type( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_fetch_backup_plan_associations_for_resource_type_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchBackupPlanAssociationsForResourceType", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchBackupsForResourceType( + _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.FetchBackupsForResourceType") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.FetchBackupsForResourceTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.FetchBackupsForResourceTypeResponse: + r"""Call the fetch backups for + resource type method over HTTP. + + Args: + request (~.backupvault.FetchBackupsForResourceTypeRequest): + The request object. Request for the + FetchBackupsForResourceType method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.FetchBackupsForResourceTypeResponse: + Response for the + FetchBackupsForResourceType method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType._get_http_options() + request, metadata = self._interceptor.pre_fetch_backups_for_resource_type( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, + "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchBackupsForResourceType", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchBackupsForResourceType", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchBackupsForResourceType._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.FetchBackupsForResourceTypeResponse() + pb_resp = backupvault.FetchBackupsForResourceTypeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_backups_for_resource_type(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_fetch_backups_for_resource_type_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupvault.FetchBackupsForResourceTypeResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_backups_for_resource_type", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchBackupsForResourceType", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchDataSourceReferencesForResourceType( + _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.FetchDataSourceReferencesForResourceType" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: + r"""Call the fetch data source + references for resource type method over HTTP. + + Args: + request (~.datasourcereference.FetchDataSourceReferencesForResourceTypeRequest): + The request object. Request for the + FetchDataSourceReferencesForResourceType + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: + Response for the + FetchDataSourceReferencesForResourceType + method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_data_source_references_for_resource_type( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, + "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchDataSourceReferencesForResourceType", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchDataSourceReferencesForResourceType", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchDataSourceReferencesForResourceType._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + pb_resp = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = ( + self._interceptor.post_fetch_data_source_references_for_resource_type( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_fetch_data_source_references_for_resource_type_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_data_source_references_for_resource_type", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchDataSourceReferencesForResourceType", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchUsableBackupVaults( + _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.FetchUsableBackupVaults") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.FetchUsableBackupVaultsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.FetchUsableBackupVaultsResponse: + r"""Call the fetch usable backup + vaults method over HTTP. + + Args: + request (~.backupvault.FetchUsableBackupVaultsRequest): + The request object. Request message for fetching usable + BackupVaults. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.FetchUsableBackupVaultsResponse: + Response message for fetching usable + BackupVaults. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults._get_http_options() + request, metadata = self._interceptor.pre_fetch_usable_backup_vaults( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, + "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchUsableBackupVaults", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchUsableBackupVaults", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchUsableBackupVaults._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.FetchUsableBackupVaultsResponse() + pb_resp = backupvault.FetchUsableBackupVaultsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_usable_backup_vaults(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_fetch_usable_backup_vaults_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupvault.FetchUsableBackupVaultsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_usable_backup_vaults", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "FetchUsableBackupVaults", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetAutoProtectionPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: autoprotectionpolicy.GetAutoProtectionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicy.AutoProtectionPolicy: + r"""Call the get auto protection + policy method over HTTP. + + Args: + request (~.autoprotectionpolicy.GetAutoProtectionPolicyRequest): + The request object. Request message for getting an + AutoProtectionPolicy. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.autoprotectionpolicy.AutoProtectionPolicy: + An AutoprotectionPolicy is a policy + resource designed to automate backup + management, moving from manual + per-resource protection to a bulk + approach. The policy dynamically + discovers and applies a specified backup + plan to all eligible resources that + match its defined scope and criteria. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_auto_protection_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, + "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetAutoProtectionPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetAutoProtectionPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetAutoProtectionPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autoprotectionpolicy.AutoProtectionPolicy() + pb_resp = autoprotectionpolicy.AutoProtectionPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_auto_protection_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_auto_protection_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + autoprotectionpolicy.AutoProtectionPolicy.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetAutoProtectionPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetAutoProtectionPolicyBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + r"""Call the get auto protection + policy binding method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest): + The request object. Request message for getting an + AutoProtectionPolicyBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.autoprotectionpolicybinding.AutoProtectionPolicyBinding: + An AutoprotectionPolicyBinding (APPA) + acts as the bridge between an + AutoprotectionPolicy and the scope + (Project, Folder, or Organization) where + the policy should be applied. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding._get_http_options() + request, metadata = ( + self._interceptor.pre_get_auto_protection_policy_binding( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, + "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetAutoProtectionPolicyBinding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetAutoProtectionPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._GetAutoProtectionPolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + pb_resp = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_auto_protection_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_auto_protection_policy_binding_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + autoprotectionpolicybinding.AutoProtectionPolicyBinding.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy_binding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetAutoProtectionPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackup(_BaseBackupDRRestTransport._BaseGetBackup, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.GetBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.backupvault.GetBackupRequest): + The request object. Request message for getting a Backup. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.Backup: + Message describing a Backup object. + """ + + http_options = _BaseBackupDRRestTransport._BaseGetBackup._get_http_options() + request, metadata = self._interceptor.pre_get_backup(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackup, + "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.Backup() + pb_resp = backupvault.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.Backup.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupPlan( + _BaseBackupDRRestTransport._BaseGetBackupPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackupPlan") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplan.GetBackupPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlan: + r"""Call the get backup plan method over HTTP. + + Args: + request (~.backupplan.GetBackupPlanRequest): + The request object. The request message for getting a ``BackupPlan``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupplan.BackupPlan: + A ``BackupPlan`` specifies some common fields, such as + ``description`` as well as one or more ``BackupRule`` + messages. Each ``BackupRule`` has a retention policy and + defines a schedule by which the system is to perform + backup workloads. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_get_backup_plan(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackupPlan, + "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackupPlan._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupplan.BackupPlan() + pb_resp = backupplan.BackupPlan.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_plan_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplan.BackupPlan.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackupPlanAssociation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplanassociation.GetBackupPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.BackupPlanAssociation: + r"""Call the get backup plan + association method over HTTP. + + Args: + request (~.backupplanassociation.GetBackupPlanAssociationRequest): + The request object. Request message for getting a + BackupPlanAssociation resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupplanassociation.BackupPlanAssociation: + A BackupPlanAssociation represents a + single BackupPlanAssociation which + contains details like workload, backup + plan etc + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_get_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, + "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackupPlanAssociation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupplanassociation.BackupPlanAssociation() + pb_resp = backupplanassociation.BackupPlanAssociation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_plan_association_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupplanassociation.BackupPlanAssociation.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupPlanRevision( + _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackupPlanRevision") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplan.GetBackupPlanRevisionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlanRevision: + r"""Call the get backup plan revision method over HTTP. + + Args: + request (~.backupplan.GetBackupPlanRevisionRequest): + The request object. The request message for getting a + ``BackupPlanRevision``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupplan.BackupPlanRevision: + ``BackupPlanRevision`` represents a snapshot of a + ``BackupPlan`` at a point in time. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanRevision._get_http_options() + request, metadata = self._interceptor.pre_get_backup_plan_revision( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, + "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlanRevision", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupPlanRevision", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackupPlanRevision._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupplan.BackupPlanRevision() + pb_resp = backupplan.BackupPlanRevision.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_plan_revision(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_plan_revision_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplan.BackupPlanRevision.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_revision", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupPlanRevision", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupVault( + _BaseBackupDRRestTransport._BaseGetBackupVault, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackupVault") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.GetBackupVaultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.BackupVault: + r"""Call the get backup vault method over HTTP. + + Args: + request (~.backupvault.GetBackupVaultRequest): + The request object. Request message for getting a + BackupVault. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.BackupVault: + Message describing a BackupVault + object. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_get_backup_vault( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackupVault, + "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupVault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupVault", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackupVault._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.BackupVault() + pb_resp = backupvault.BackupVault.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_vault(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_vault_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.BackupVault.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_vault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBackupVault", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBindingMatchingResource( + _BaseBackupDRRestTransport._BaseGetBindingMatchingResource, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBindingMatchingResource") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bindingmatchingresource.GetBindingMatchingResourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bindingmatchingresource.BindingMatchingResource: + r"""Call the get binding matching + resource method over HTTP. + + Args: + request (~.bindingmatchingresource.GetBindingMatchingResourceRequest): + The request object. Request message for getting a + BindingMatchingResource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.bindingmatchingresource.BindingMatchingResource: + BindingMatchingResource contains the + details of a resource that matches the + criteria of a binding. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetBindingMatchingResource._get_http_options() + request, metadata = self._interceptor.pre_get_binding_matching_resource( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBindingMatchingResource, + "_BaseGetBindingMatchingResource__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBindingMatchingResource", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBindingMatchingResource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBindingMatchingResource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bindingmatchingresource.BindingMatchingResource() + pb_resp = bindingmatchingresource.BindingMatchingResource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_binding_matching_resource(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_binding_matching_resource_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bindingmatchingresource.BindingMatchingResource.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_binding_matching_resource", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetBindingMatchingResource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDataSource( + _BaseBackupDRRestTransport._BaseGetDataSource, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetDataSource") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.GetDataSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.DataSource: + r"""Call the get data source method over HTTP. + + Args: + request (~.backupvault.GetDataSourceRequest): + The request object. Request message for getting a + DataSource instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.DataSource: + Message describing a DataSource + object. Datasource object used to + represent Datasource details for both + admin and basic view. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetDataSource._get_http_options() + ) + request, metadata = self._interceptor.pre_get_data_source(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetDataSource, + "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetDataSource", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetDataSource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.DataSource() + pb_resp = backupvault.DataSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_data_source(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_data_source_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.DataSource.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_data_source", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDataSourceReference( + _BaseBackupDRRestTransport._BaseGetDataSourceReference, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetDataSourceReference") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: datasourcereference.GetDataSourceReferenceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasourcereference.DataSourceReference: + r"""Call the get data source reference method over HTTP. + + Args: + request (~.datasourcereference.GetDataSourceReferenceRequest): + The request object. Request for the + GetDataSourceReference method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.datasourcereference.DataSourceReference: + DataSourceReference is a reference to + a DataSource resource. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetDataSourceReference._get_http_options() + request, metadata = self._interceptor.pre_get_data_source_reference( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetDataSourceReference, + "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetDataSourceReference", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetDataSourceReference", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetDataSourceReference._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = datasourcereference.DataSourceReference() + pb_resp = datasourcereference.DataSourceReference.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_data_source_reference(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_data_source_reference_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasourcereference.DataSourceReference.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_data_source_reference", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetDataSourceReference", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetManagementServer( + _BaseBackupDRRestTransport._BaseGetManagementServer, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetManagementServer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupdr.GetManagementServerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupdr.ManagementServer: + r"""Call the get management server method over HTTP. + + Args: + request (~.backupdr.GetManagementServerRequest): + The request object. Request message for getting a + management server instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupdr.ManagementServer: + ManagementServer describes a single + BackupDR ManagementServer instance. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetManagementServer._get_http_options() + ) + request, metadata = self._interceptor.pre_get_management_server( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetManagementServer, + "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetManagementServer", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetManagementServer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetManagementServer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupdr.ManagementServer() + pb_resp = backupdr.ManagementServer.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_management_server(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_management_server_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupdr.ManagementServer.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_management_server", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetManagementServer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InitializeService( + _BaseBackupDRRestTransport._BaseInitializeService, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.InitializeService") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupdr.InitializeServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the initialize service method over HTTP. + + Args: + request (~.backupdr.InitializeServiceRequest): + The request object. Request message for initializing the + service. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseInitializeService._get_http_options() + ) + request, metadata = self._interceptor.pre_initialize_service( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseInitializeService, + "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.InitializeService", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitializeService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._InitializeService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_initialize_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_initialize_service_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.initialize_service", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitializeService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InitiateDeleteAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.InitiateDeleteAutoProtectionPolicyBinding" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the initiate delete auto + protection policy binding method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest): + The request object. Request message for initiating delete + of an AutoProtectionPolicyBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding._get_http_options() + request, metadata = ( + self._interceptor.pre_initiate_delete_auto_protection_policy_binding( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, + "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.InitiateDeleteAutoProtectionPolicyBinding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._InitiateDeleteAutoProtectionPolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = ( + self._interceptor.post_initiate_delete_auto_protection_policy_binding( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_initiate_delete_auto_protection_policy_binding_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.initiate_delete_auto_protection_policy_binding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAppliedAutoProtectionPolicies( + _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, + BackupDRRestStub, + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListAppliedAutoProtectionPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + r"""Call the list applied auto + protection policies method over HTTP. + + Args: + request (~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest): + The request object. Request message for listing + AppliedAutoProtectionPolicies. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + Response message for + ListAppliedAutoProtectionPolicies. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies._get_http_options() + request, metadata = ( + self._interceptor.pre_list_applied_auto_protection_policies( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, + "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListAppliedAutoProtectionPolicies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAppliedAutoProtectionPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._ListAppliedAutoProtectionPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + pb_resp = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_applied_auto_protection_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_applied_auto_protection_policies_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_applied_auto_protection_policies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAppliedAutoProtectionPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAutoProtectionPolicies( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListAutoProtectionPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + r"""Call the list auto protection + policies method over HTTP. + + Args: + request (~.autoprotectionpolicy.ListAutoProtectionPoliciesRequest): + The request object. Request message for + ListAutoProtectionPolicies. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + Response message for + ListAutoProtectionPolicies. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies._get_http_options() + request, metadata = self._interceptor.pre_list_auto_protection_policies( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, + "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListAutoProtectionPolicies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAutoProtectionPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListAutoProtectionPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + pb_resp = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_auto_protection_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_auto_protection_policies_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAutoProtectionPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAutoProtectionPolicyBindings( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, + BackupDRRestStub, + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListAutoProtectionPolicyBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + r"""Call the list auto protection + policy bindings method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest): + The request object. Request message for + ListAutoProtectionPolicyBindings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + Response message for + ListAutoProtectionPolicyBindings. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings._get_http_options() + request, metadata = ( + self._interceptor.pre_list_auto_protection_policy_bindings( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, + "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListAutoProtectionPolicyBindings", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAutoProtectionPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._ListAutoProtectionPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + pb_resp = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_auto_protection_policy_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_auto_protection_policy_bindings_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policy_bindings", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAutoProtectionPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupPlanAssociations( + _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupPlanAssociations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplanassociation.ListBackupPlanAssociationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.ListBackupPlanAssociationsResponse: + r"""Call the list backup plan + associations method over HTTP. + + Args: + request (~.backupplanassociation.ListBackupPlanAssociationsRequest): + The request object. Request message for List + BackupPlanAssociation + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupplanassociation.ListBackupPlanAssociationsResponse: + Response message for List + BackupPlanAssociation + + """ + + http_options = _BaseBackupDRRestTransport._BaseListBackupPlanAssociations._get_http_options() + request, metadata = self._interceptor.pre_list_backup_plan_associations( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, + "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupPlanAssociations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanAssociations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupPlanAssociations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupplanassociation.ListBackupPlanAssociationsResponse() + pb_resp = backupplanassociation.ListBackupPlanAssociationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_plan_associations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_backup_plan_associations_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplanassociation.ListBackupPlanAssociationsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_associations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanAssociations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupPlanRevisions( + _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupPlanRevisions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplan.ListBackupPlanRevisionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.ListBackupPlanRevisionsResponse: + r"""Call the list backup plan + revisions method over HTTP. + + Args: + request (~.backupplan.ListBackupPlanRevisionsRequest): + The request object. The request message for getting a list of + ``BackupPlanRevision``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupplan.ListBackupPlanRevisionsResponse: + The response message for getting a list of + ``BackupPlanRevision``. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListBackupPlanRevisions._get_http_options() + request, metadata = self._interceptor.pre_list_backup_plan_revisions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, + "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupPlanRevisions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanRevisions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupPlanRevisions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupplan.ListBackupPlanRevisionsResponse() + pb_resp = backupplan.ListBackupPlanRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_plan_revisions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backup_plan_revisions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupplan.ListBackupPlanRevisionsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_revisions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanRevisions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupPlans( + _BaseBackupDRRestTransport._BaseListBackupPlans, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupPlans") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupplan.ListBackupPlansRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.ListBackupPlansResponse: + r"""Call the list backup plans method over HTTP. + + Args: + request (~.backupplan.ListBackupPlansRequest): + The request object. The request message for getting a list ``BackupPlan``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupplan.ListBackupPlansResponse: + The response message for getting a list of + ``BackupPlan``. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListBackupPlans._get_http_options() + ) + request, metadata = self._interceptor.pre_list_backup_plans( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupPlans, + "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupPlans", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlans", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupPlans._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupplan.ListBackupPlansResponse() + pb_resp = backupplan.ListBackupPlansResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_plans(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backup_plans_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplan.ListBackupPlansResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plans", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlans", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackups(_BaseBackupDRRestTransport._BaseListBackups, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackups") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.ListBackupsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.backupvault.ListBackupsRequest): + The request object. Request message for listing Backups. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.ListBackupsResponse: + Response message for listing Backups. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListBackups._get_http_options() + ) + request, metadata = self._interceptor.pre_list_backups(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackups, + "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackups", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackups._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.ListBackupsResponse() + pb_resp = backupvault.ListBackupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backups(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backups_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.ListBackupsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backups", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupVaults( + _BaseBackupDRRestTransport._BaseListBackupVaults, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupVaults") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.ListBackupVaultsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.ListBackupVaultsResponse: + r"""Call the list backup vaults method over HTTP. + + Args: + request (~.backupvault.ListBackupVaultsRequest): + The request object. Request message for listing + backupvault stores. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.ListBackupVaultsResponse: + Response message for listing + BackupVaults. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListBackupVaults._get_http_options() + ) + request, metadata = self._interceptor.pre_list_backup_vaults( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupVaults, + "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupVaults", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupVaults", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupVaults._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.ListBackupVaultsResponse() + pb_resp = backupvault.ListBackupVaultsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_vaults(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backup_vaults_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.ListBackupVaultsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_vaults", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupVaults", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBindingMatchingResources( + _BaseBackupDRRestTransport._BaseListBindingMatchingResources, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBindingMatchingResources") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bindingmatchingresource.ListBindingMatchingResourcesResponse: + r"""Call the list binding matching + resources method over HTTP. + + Args: + request (~.bindingmatchingresource.ListBindingMatchingResourcesRequest): + The request object. Request message for List + BindingMatchingResources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.bindingmatchingresource.ListBindingMatchingResourcesResponse: + The response message for getting a list of + ``BindingMatchingResources``. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListBindingMatchingResources._get_http_options() + request, metadata = self._interceptor.pre_list_binding_matching_resources( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBindingMatchingResources, + "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBindingMatchingResources", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBindingMatchingResources", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._ListBindingMatchingResources._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bindingmatchingresource.ListBindingMatchingResourcesResponse() + pb_resp = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_binding_matching_resources(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_binding_matching_resources_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bindingmatchingresource.ListBindingMatchingResourcesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_binding_matching_resources", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBindingMatchingResources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDataSourceReferences( + _BaseBackupDRRestTransport._BaseListDataSourceReferences, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListDataSourceReferences") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: datasourcereference.ListDataSourceReferencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasourcereference.ListDataSourceReferencesResponse: + r"""Call the list data source + references method over HTTP. + + Args: + request (~.datasourcereference.ListDataSourceReferencesRequest): + The request object. Request for the + ListDataSourceReferences method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.datasourcereference.ListDataSourceReferencesResponse: + Response for the + ListDataSourceReferences method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListDataSourceReferences._get_http_options() + request, metadata = self._interceptor.pre_list_data_source_references( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListDataSourceReferences, + "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListDataSourceReferences", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListDataSourceReferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListDataSourceReferences._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = datasourcereference.ListDataSourceReferencesResponse() + pb_resp = datasourcereference.ListDataSourceReferencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_data_source_references(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_data_source_references_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + datasourcereference.ListDataSourceReferencesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_data_source_references", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListDataSourceReferences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDataSources( + _BaseBackupDRRestTransport._BaseListDataSources, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListDataSources") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupvault.ListDataSourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.ListDataSourcesResponse: + r"""Call the list data sources method over HTTP. + + Args: + request (~.backupvault.ListDataSourcesRequest): + The request object. Request message for listing + DataSources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupvault.ListDataSourcesResponse: + Response message for listing + DataSources. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListDataSources._get_http_options() + ) + request, metadata = self._interceptor.pre_list_data_sources( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListDataSources, + "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListDataSources", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListDataSources", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListDataSources._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupvault.ListDataSourcesResponse() + pb_resp = backupvault.ListDataSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_data_sources(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_data_sources_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.ListDataSourcesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_data_sources", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListDataSources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListManagementServers( + _BaseBackupDRRestTransport._BaseListManagementServers, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListManagementServers") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: backupdr.ListManagementServersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupdr.ListManagementServersResponse: + r"""Call the list management servers method over HTTP. + + Args: + request (~.backupdr.ListManagementServersRequest): + The request object. Request message for listing + management servers. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.backupdr.ListManagementServersResponse: + Response message for listing + management servers. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListManagementServers._get_http_options() + request, metadata = self._interceptor.pre_list_management_servers( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListManagementServers, + "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListManagementServers", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListManagementServers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListManagementServers._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = backupdr.ListManagementServersResponse() + pb_resp = backupdr.ListManagementServersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_management_servers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_management_servers_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupdr.ListManagementServersResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_management_servers", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListManagementServers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RestoreBackup( + _BaseBackupDRRestTransport._BaseRestoreBackup, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.RestoreBackup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupvault.RestoreBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the restore backup method over HTTP. + + Args: + request (~.backupvault.RestoreBackupRequest): + The request object. Request message for restoring from a + Backup. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseRestoreBackup._get_http_options() + ) + request, metadata = self._interceptor.pre_restore_backup(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseRestoreBackup, + "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.RestoreBackup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "RestoreBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._RestoreBackup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_restore_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_restore_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.restore_backup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "RestoreBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _TriggerBackup( + _BaseBackupDRRestTransport._BaseTriggerBackup, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.TriggerBackup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupplanassociation.TriggerBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the trigger backup method over HTTP. + + Args: + request (~.backupplanassociation.TriggerBackupRequest): + The request object. Request message for triggering a + backup. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseTriggerBackup._get_http_options() + ) + request, metadata = self._interceptor.pre_trigger_backup(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseTriggerBackup, + "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.TriggerBackup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "TriggerBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._TriggerBackup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_trigger_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_trigger_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.trigger_backup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "TriggerBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseUpdateAutoProtectionPolicy, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateAutoProtectionPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update auto protection + policy method over HTTP. + + Args: + request (~.autoprotectionpolicy.UpdateAutoProtectionPolicyRequest): + The request object. Request message for updating an + AutoProtectionPolicy. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseUpdateAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_update_auto_protection_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateAutoProtectionPolicy, + "_BaseUpdateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateAutoProtectionPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateAutoProtectionPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateAutoProtectionPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_auto_protection_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_auto_protection_policy_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_auto_protection_policy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateAutoProtectionPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBackup(_BaseBackupDRRestTransport._BaseUpdateBackup, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateBackup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupvault.UpdateBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update backup method over HTTP. + + Args: + request (~.backupvault.UpdateBackupRequest): + The request object. Request message for updating a + Backup. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseUpdateBackup._get_http_options() + ) + request, metadata = self._interceptor.pre_update_backup(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateBackup, + "_BaseUpdateBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateBackup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateBackup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_backup", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBackupPlan( + _BaseBackupDRRestTransport._BaseUpdateBackupPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateBackupPlan") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupplan.UpdateBackupPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update backup plan method over HTTP. + + Args: + request (~.backupplan.UpdateBackupPlanRequest): + The request object. Request message for updating a backup + plan. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseUpdateBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_update_backup_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateBackupPlan, + "_BaseUpdateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateBackupPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateBackupPlan._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_backup_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_backup_plan_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_backup_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseUpdateBackupPlanAssociation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateBackupPlanAssociation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupplanassociation.UpdateBackupPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update backup plan + association method over HTTP. + + Args: + request (~.backupplanassociation.UpdateBackupPlanAssociationRequest): + The request object. Request message for updating a backup + plan association. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseUpdateBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_update_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateBackupPlanAssociation, + "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateBackupPlanAssociation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_backup_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_backup_plan_association_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBackupVault( + _BaseBackupDRRestTransport._BaseUpdateBackupVault, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateBackupVault") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupvault.UpdateBackupVaultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update backup vault method over HTTP. + + Args: + request (~.backupvault.UpdateBackupVaultRequest): + The request object. Request message for updating a + BackupVault. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseUpdateBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_update_backup_vault( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateBackupVault, + "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateBackupVault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupVault", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateBackupVault._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_backup_vault(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_backup_vault_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_backup_vault", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupVault", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateDataSource( + _BaseBackupDRRestTransport._BaseUpdateDataSource, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateDataSource") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: backupvault.UpdateDataSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update data source method over HTTP. + + Args: + request (~.backupvault.UpdateDataSourceRequest): + The request object. Request message for updating a data + source instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseUpdateDataSource._get_http_options() + ) + request, metadata = self._interceptor.pre_update_data_source( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateDataSource, + "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateDataSource", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateDataSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateDataSource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_data_source(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_data_source_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_data_source", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateDataSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAutoProtectionPolicyBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_backup_plan( + self, + ) -> Callable[[backupplan.CreateBackupPlanRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBackupPlan(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.CreateBackupPlanAssociationRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBackupPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_backup_vault( + self, + ) -> Callable[[backupvault.CreateBackupVaultRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBackupVault(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_management_server( + self, + ) -> Callable[[backupdr.CreateManagementServerRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateManagementServer( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_backup( + self, + ) -> Callable[[backupvault.DeleteBackupRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup_plan( + self, + ) -> Callable[[backupplan.DeleteBackupPlanRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackupPlan(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.DeleteBackupPlanAssociationRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackupPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_backup_vault( + self, + ) -> Callable[[backupvault.DeleteBackupVaultRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackupVault(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_management_server( + self, + ) -> Callable[[backupdr.DeleteManagementServerRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteManagementServer( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_backup_plan_associations_for_resource_type( + self, + ) -> Callable[ + [backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest], + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchBackupPlanAssociationsForResourceType( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_backups_for_resource_type( + self, + ) -> Callable[ + [backupvault.FetchBackupsForResourceTypeRequest], + backupvault.FetchBackupsForResourceTypeResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchBackupsForResourceType( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_data_source_references_for_resource_type( + self, + ) -> Callable[ + [datasourcereference.FetchDataSourceReferencesForResourceTypeRequest], + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchDataSourceReferencesForResourceType( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_usable_backup_vaults( + self, + ) -> Callable[ + [backupvault.FetchUsableBackupVaultsRequest], + backupvault.FetchUsableBackupVaultsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchUsableBackupVaults( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + autoprotectionpolicy.AutoProtectionPolicy, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAutoProtectionPolicyBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_backup( + self, + ) -> Callable[[backupvault.GetBackupRequest], backupvault.Backup]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup_plan( + self, + ) -> Callable[[backupplan.GetBackupPlanRequest], backupplan.BackupPlan]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackupPlan(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.GetBackupPlanAssociationRequest], + backupplanassociation.BackupPlanAssociation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackupPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_backup_plan_revision( + self, + ) -> Callable[ + [backupplan.GetBackupPlanRevisionRequest], backupplan.BackupPlanRevision + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackupPlanRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup_vault( + self, + ) -> Callable[[backupvault.GetBackupVaultRequest], backupvault.BackupVault]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBackupVault(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_binding_matching_resource( + self, + ) -> Callable[ + [bindingmatchingresource.GetBindingMatchingResourceRequest], + bindingmatchingresource.BindingMatchingResource, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBindingMatchingResource( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_data_source( + self, + ) -> Callable[[backupvault.GetDataSourceRequest], backupvault.DataSource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_source_reference( + self, + ) -> Callable[ + [datasourcereference.GetDataSourceReferenceRequest], + datasourcereference.DataSourceReference, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataSourceReference( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_management_server( + self, + ) -> Callable[[backupdr.GetManagementServerRequest], backupdr.ManagementServer]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetManagementServer(self._session, self._host, self._interceptor) # type: ignore + + @property + def initialize_service( + self, + ) -> Callable[[backupdr.InitializeServiceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InitializeService(self._session, self._host, self._interceptor) # type: ignore + + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InitiateDeleteAutoProtectionPolicyBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAppliedAutoProtectionPolicies( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAutoProtectionPolicies( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAutoProtectionPolicyBindings( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_backup_plan_associations( + self, + ) -> Callable[ + [backupplanassociation.ListBackupPlanAssociationsRequest], + backupplanassociation.ListBackupPlanAssociationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackupPlanAssociations( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_backup_plan_revisions( + self, + ) -> Callable[ + [backupplan.ListBackupPlanRevisionsRequest], + backupplan.ListBackupPlanRevisionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackupPlanRevisions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_backup_plans( + self, + ) -> Callable[ + [backupplan.ListBackupPlansRequest], backupplan.ListBackupPlansResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackupPlans(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups( + self, + ) -> Callable[[backupvault.ListBackupsRequest], backupvault.ListBackupsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackups(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backup_vaults( + self, + ) -> Callable[ + [backupvault.ListBackupVaultsRequest], backupvault.ListBackupVaultsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBackupVaults(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + bindingmatchingresource.ListBindingMatchingResourcesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBindingMatchingResources( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_data_source_references( + self, + ) -> Callable[ + [datasourcereference.ListDataSourceReferencesRequest], + datasourcereference.ListDataSourceReferencesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDataSourceReferences( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_data_sources( + self, + ) -> Callable[ + [backupvault.ListDataSourcesRequest], backupvault.ListDataSourcesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDataSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_management_servers( + self, + ) -> Callable[ + [backupdr.ListManagementServersRequest], backupdr.ListManagementServersResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListManagementServers(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_backup( + self, + ) -> Callable[[backupvault.RestoreBackupRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def trigger_backup( + self, + ) -> Callable[ + [backupplanassociation.TriggerBackupRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TriggerBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_backup( + self, + ) -> Callable[[backupvault.UpdateBackupRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_backup_plan( + self, + ) -> Callable[[backupplan.UpdateBackupPlanRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBackupPlan(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_backup_plan_association( + self, + ) -> Callable[ + [backupplanassociation.UpdateBackupPlanAssociationRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBackupPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_backup_vault( + self, + ) -> Callable[[backupvault.UpdateBackupVaultRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBackupVault(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_source( + self, + ) -> Callable[[backupvault.UpdateDataSourceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDataSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseBackupDRRestTransport._BaseGetLocation, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetLocation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetLocation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseBackupDRRestTransport._BaseListLocations, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListLocations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListLocations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseBackupDRRestTransport._BaseGetIamPolicy, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseBackupDRRestTransport._BaseSetIamPolicy, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseSetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseBackupDRRestTransport._BaseTestIamPermissions, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseTestIamPermissions._get_http_options() + ) + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseTestIamPermissions, + "_BaseTestIamPermissions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseBackupDRRestTransport._BaseCancelOperation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseCancelOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CancelOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseBackupDRRestTransport._BaseDeleteOperation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseDeleteOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteOperation, + "_BaseDeleteOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseBackupDRRestTransport._BaseGetOperation, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseBackupDRRestTransport._BaseListOperations, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListOperations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListOperations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDRAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("BackupDRRestTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest_base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest_base.py new file mode 100644 index 000000000000..62ae1ad6bd98 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest_base.py @@ -0,0 +1,1066 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + bindingmatchingresource, + datasourcereference, +) + +from .base import DEFAULT_CLIENT_INFO, BackupDRTransport + + +class _BaseBackupDRRestTransport(BackupDRTransport): + """Base REST backend transport for BackupDR. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "autoProtectionPolicyId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/autoProtectionPolicies", + "body": "auto_protection_policy", + }, + ] + return http_options + + class _BaseCreateAutoProtectionPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "autoProtectionPolicyBindingId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/autoProtectionPolicies/*}/bindings", + "body": "auto_protection_policy_binding", + }, + ] + return http_options + + class _BaseCreateBackupPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "backupPlanId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupPlans", + "body": "backup_plan", + }, + ] + return http_options + + class _BaseCreateBackupPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "backupPlanAssociationId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupPlanAssociations", + "body": "backup_plan_association", + }, + ] + return http_options + + class _BaseCreateBackupVault: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "backupVaultId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupVaults", + "body": "backup_vault", + }, + ] + return http_options + + class _BaseCreateManagementServer: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "managementServerId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/managementServers", + "body": "management_server", + }, + ] + return http_options + + class _BaseDeleteAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*}", + }, + ] + return http_options + + class _BaseDeleteBackup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}", + }, + ] + return http_options + + class _BaseDeleteBackupPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/backupPlans/*}", + }, + ] + return http_options + + class _BaseDeleteBackupPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/backupPlanAssociations/*}", + }, + ] + return http_options + + class _BaseDeleteBackupVault: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/backupVaults/*}", + }, + ] + return http_options + + class _BaseDeleteManagementServer: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/managementServers/*}", + }, + ] + return http_options + + class _BaseFetchBackupPlanAssociationsForResourceType: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "resourceType": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupPlanAssociations:fetchForResourceType", + }, + ] + return http_options + + class _BaseFetchBackupsForResourceType: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "resourceType": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups:fetchForResourceType", + }, + ] + return http_options + + class _BaseFetchDataSourceReferencesForResourceType: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "resourceType": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/dataSourceReferences:fetchForResourceType", + }, + ] + return http_options + + class _BaseFetchUsableBackupVaults: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupVaults:fetchUsable", + }, + ] + return http_options + + class _BaseGetAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*}", + }, + ] + return http_options + + class _BaseGetAutoProtectionPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}", + }, + ] + return http_options + + class _BaseGetBackup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}", + }, + ] + return http_options + + class _BaseGetBackupPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/backupPlans/*}", + }, + ] + return http_options + + class _BaseGetBackupPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/backupPlanAssociations/*}", + }, + ] + return http_options + + class _BaseGetBackupPlanRevision: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/backupPlans/*/revisions/*}", + }, + ] + return http_options + + class _BaseGetBackupVault: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/backupVaults/*}", + }, + ] + return http_options + + class _BaseGetBindingMatchingResource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*/matchingResources/*}", + }, + ] + return http_options + + class _BaseGetDataSource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*}", + }, + ] + return http_options + + class _BaseGetDataSourceReference: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/dataSourceReferences/*}", + }, + ] + return http_options + + class _BaseGetManagementServer: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/managementServers/*}", + }, + ] + return http_options + + class _BaseInitializeService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/serviceConfig}:initialize", + "body": "*", + }, + ] + return http_options + + class _BaseInitiateDeleteAutoProtectionPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}:initiateDelete", + "body": "*", + }, + ] + return http_options + + class _BaseListAppliedAutoProtectionPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/appliedAutoProtectionPolicies", + }, + ] + return http_options + + class _BaseListAutoProtectionPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/autoProtectionPolicies", + }, + ] + return http_options + + class _BaseListAutoProtectionPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/autoProtectionPolicies/*}/bindings", + }, + ] + return http_options + + class _BaseListBackupPlanAssociations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupPlanAssociations", + }, + ] + return http_options + + class _BaseListBackupPlanRevisions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/backupPlans/*}/revisions", + }, + ] + return http_options + + class _BaseListBackupPlans: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupPlans", + }, + ] + return http_options + + class _BaseListBackups: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups", + }, + ] + return http_options + + class _BaseListBackupVaults: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/backupVaults", + }, + ] + return http_options + + class _BaseListBindingMatchingResources: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}/matchingResources", + }, + ] + return http_options + + class _BaseListDataSourceReferences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/dataSourceReferences", + }, + ] + return http_options + + class _BaseListDataSources: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/backupVaults/*}/dataSources", + }, + ] + return http_options + + class _BaseListManagementServers: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/managementServers", + }, + ] + return http_options + + class _BaseRestoreBackup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}:restore", + "body": "*", + }, + ] + return http_options + + class _BaseTriggerBackup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/backupPlanAssociations/*}:triggerBackup", + "body": "*", + }, + ] + return http_options + + class _BaseUpdateAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{auto_protection_policy.name=projects/*/locations/*/autoProtectionPolicies/*}", + "body": "auto_protection_policy", + }, + ] + return http_options + + class _BaseUpdateBackup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{backup.name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}", + "body": "backup", + }, + ] + return http_options + + class _BaseUpdateBackupPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{backup_plan.name=projects/*/locations/*/backupPlans/*}", + "body": "backup_plan", + }, + ] + return http_options + + class _BaseUpdateBackupPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{backup_plan_association.name=projects/*/locations/*/backupPlanAssociations/*}", + "body": "backup_plan_association", + }, + ] + return http_options + + class _BaseUpdateBackupVault: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{backup_vault.name=projects/*/locations/*/backupVaults/*}", + "body": "backup_vault", + }, + ] + return http_options + + class _BaseUpdateDataSource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{data_source.name=projects/*/locations/*/backupVaults/*/dataSources/*}", + "body": "data_source", + }, + ] + return http_options + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{resource=projects/*/locations/*/managementServers/*}:getIamPolicy", + }, + ] + return http_options + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{resource=projects/*/locations/*/managementServers/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{resource=projects/*/locations/*/managementServers/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseBackupDRRestTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/__init__.py new file mode 100644 index 000000000000..111495ef1b1a --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import BackupDrProtectionSummaryAsyncClient +from .client import BackupDrProtectionSummaryClient + +__all__ = ( + "BackupDrProtectionSummaryClient", + "BackupDrProtectionSummaryAsyncClient", +) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/async_client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/async_client.py new file mode 100644 index 000000000000..95b0e235128e --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/async_client.py @@ -0,0 +1,1145 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.backupdr_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.backupdr_v1beta.services.backup_dr_protection_summary import pagers +from google.cloud.backupdr_v1beta.types import protection_summary + +from .client import BackupDrProtectionSummaryClient +from .transports.base import DEFAULT_CLIENT_INFO, BackupDrProtectionSummaryTransport +from .transports.grpc_asyncio import BackupDrProtectionSummaryGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class BackupDrProtectionSummaryAsyncClient: + """The Protection Summary service.""" + + _client: BackupDrProtectionSummaryClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = BackupDrProtectionSummaryClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = BackupDrProtectionSummaryClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + BackupDrProtectionSummaryClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = BackupDrProtectionSummaryClient._DEFAULT_UNIVERSE + + resource_backup_config_path = staticmethod( + BackupDrProtectionSummaryClient.resource_backup_config_path + ) + parse_resource_backup_config_path = staticmethod( + BackupDrProtectionSummaryClient.parse_resource_backup_config_path + ) + common_billing_account_path = staticmethod( + BackupDrProtectionSummaryClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + BackupDrProtectionSummaryClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + BackupDrProtectionSummaryClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + BackupDrProtectionSummaryClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + BackupDrProtectionSummaryClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + BackupDrProtectionSummaryClient.parse_common_organization_path + ) + common_project_path = staticmethod( + BackupDrProtectionSummaryClient.common_project_path + ) + parse_common_project_path = staticmethod( + BackupDrProtectionSummaryClient.parse_common_project_path + ) + common_location_path = staticmethod( + BackupDrProtectionSummaryClient.common_location_path + ) + parse_common_location_path = staticmethod( + BackupDrProtectionSummaryClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDrProtectionSummaryAsyncClient: The constructed client. + """ + sa_info_func = ( + BackupDrProtectionSummaryClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(BackupDrProtectionSummaryAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDrProtectionSummaryAsyncClient: The constructed client. + """ + sa_file_func = ( + BackupDrProtectionSummaryClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + BackupDrProtectionSummaryAsyncClient, filename, *args, **kwargs + ) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return BackupDrProtectionSummaryClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> BackupDrProtectionSummaryTransport: + """Returns the transport used by the client instance. + + Returns: + BackupDrProtectionSummaryTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = BackupDrProtectionSummaryClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + BackupDrProtectionSummaryTransport, + Callable[..., BackupDrProtectionSummaryTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the backup dr protection summary async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,BackupDrProtectionSummaryTransport,Callable[..., BackupDrProtectionSummaryTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the BackupDrProtectionSummaryTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = BackupDrProtectionSummaryClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient`.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "credentialsType": None, + }, + ) + + async def list_resource_backup_configs( + self, + request: Optional[ + Union[protection_summary.ListResourceBackupConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListResourceBackupConfigsAsyncPager: + r"""Lists ResourceBackupConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_resource_backup_configs(): + # Create a client + client = backupdr_v1beta.BackupDrProtectionSummaryAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListResourceBackupConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_backup_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsRequest, dict]]): + The request object. Request for + ListResourceBackupConfigs. + parent (:class:`str`): + Required. The project and location for which to retrieve + resource backup configs. Format: + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.pagers.ListResourceBackupConfigsAsyncPager: + Response for + ListResourceBackupConfigs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, protection_summary.ListResourceBackupConfigsRequest): + request = protection_summary.ListResourceBackupConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_resource_backup_configs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListResourceBackupConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "BackupDrProtectionSummaryAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("BackupDrProtectionSummaryAsyncClient",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/client.py new file mode 100644 index 000000000000..c0fbdf86a62e --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/client.py @@ -0,0 +1,1460 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.backupdr_v1beta import gapic_version as package_version +from google.cloud.backupdr_v1beta._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.backupdr_v1beta.services.backup_dr_protection_summary import pagers +from google.cloud.backupdr_v1beta.types import protection_summary + +from .transports.base import DEFAULT_CLIENT_INFO, BackupDrProtectionSummaryTransport +from .transports.grpc import BackupDrProtectionSummaryGrpcTransport +from .transports.grpc_asyncio import BackupDrProtectionSummaryGrpcAsyncIOTransport +from .transports.rest import BackupDrProtectionSummaryRestTransport + + +class BackupDrProtectionSummaryClientMeta(type): + """Metaclass for the BackupDrProtectionSummary client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[BackupDrProtectionSummaryTransport]] + _transport_registry["grpc"] = BackupDrProtectionSummaryGrpcTransport + _transport_registry["grpc_asyncio"] = BackupDrProtectionSummaryGrpcAsyncIOTransport + _transport_registry["rest"] = BackupDrProtectionSummaryRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[BackupDrProtectionSummaryTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class BackupDrProtectionSummaryClient(metaclass=BackupDrProtectionSummaryClientMeta): + """The Protection Summary service.""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "backupdr.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "backupdr.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDrProtectionSummaryClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + BackupDrProtectionSummaryClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> BackupDrProtectionSummaryTransport: + """Returns the transport used by the client instance. + + Returns: + BackupDrProtectionSummaryTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def resource_backup_config_path( + project: str, + location: str, + resource_backup_config: str, + ) -> str: + """Returns a fully-qualified resource_backup_config string.""" + return "projects/{project}/locations/{location}/resourceBackupConfigs/{resource_backup_config}".format( + project=project, + location=location, + resource_backup_config=resource_backup_config, + ) + + @staticmethod + def parse_resource_backup_config_path(path: str) -> Dict[str, str]: + """Parses a resource_backup_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/resourceBackupConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + BackupDrProtectionSummaryTransport, + Callable[..., BackupDrProtectionSummaryTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the backup dr protection summary client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,BackupDrProtectionSummaryTransport,Callable[..., BackupDrProtectionSummaryTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the BackupDrProtectionSummaryTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = ( + BackupDrProtectionSummaryClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=BackupDrProtectionSummaryClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, BackupDrProtectionSummaryTransport) + if transport_provided: + # transport is a BackupDrProtectionSummaryTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(BackupDrProtectionSummaryTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=BackupDrProtectionSummaryClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=BackupDrProtectionSummaryClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=BackupDrProtectionSummaryClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[BackupDrProtectionSummaryTransport], + Callable[..., BackupDrProtectionSummaryTransport], + ] = ( + BackupDrProtectionSummaryClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., BackupDrProtectionSummaryTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient`.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "credentialsType": None, + }, + ) + + def list_resource_backup_configs( + self, + request: Optional[ + Union[protection_summary.ListResourceBackupConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListResourceBackupConfigsPager: + r"""Lists ResourceBackupConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_resource_backup_configs(): + # Create a client + client = backupdr_v1beta.BackupDrProtectionSummaryClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListResourceBackupConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_backup_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsRequest, dict]): + The request object. Request for + ListResourceBackupConfigs. + parent (str): + Required. The project and location for which to retrieve + resource backup configs. Format: + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.pagers.ListResourceBackupConfigsPager: + Response for + ListResourceBackupConfigs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, protection_summary.ListResourceBackupConfigsRequest): + request = protection_summary.ListResourceBackupConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_resource_backup_configs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListResourceBackupConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "BackupDrProtectionSummaryClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("BackupDrProtectionSummaryClient",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/pagers.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/pagers.py new file mode 100644 index 000000000000..a0fe8e6c2a57 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/pagers.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.backupdr_v1beta.types import protection_summary + + +class ListResourceBackupConfigsPager: + """A pager for iterating through ``list_resource_backup_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_backup_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceBackupConfigs`` requests and continue to iterate + through the ``resource_backup_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., protection_summary.ListResourceBackupConfigsResponse], + request: protection_summary.ListResourceBackupConfigsRequest, + response: protection_summary.ListResourceBackupConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = protection_summary.ListResourceBackupConfigsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[protection_summary.ListResourceBackupConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[protection_summary.ResourceBackupConfig]: + for page in self.pages: + yield from page.resource_backup_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListResourceBackupConfigsAsyncPager: + """A pager for iterating through ``list_resource_backup_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_backup_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceBackupConfigs`` requests and continue to iterate + through the ``resource_backup_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[protection_summary.ListResourceBackupConfigsResponse] + ], + request: protection_summary.ListResourceBackupConfigsRequest, + response: protection_summary.ListResourceBackupConfigsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = protection_summary.ListResourceBackupConfigsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[protection_summary.ListResourceBackupConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[protection_summary.ResourceBackupConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_backup_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/README.rst b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/README.rst new file mode 100644 index 000000000000..272fcea48f88 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``BackupDrProtectionSummaryTransport`` is the ABC for all transports. + +- public child ``BackupDrProtectionSummaryGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``BackupDrProtectionSummaryGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseBackupDrProtectionSummaryRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``BackupDrProtectionSummaryRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/__init__.py new file mode 100644 index 000000000000..73bdc3396d51 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/__init__.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import BackupDrProtectionSummaryTransport +from .grpc import BackupDrProtectionSummaryGrpcTransport +from .grpc_asyncio import BackupDrProtectionSummaryGrpcAsyncIOTransport +from .rest import ( + BackupDrProtectionSummaryRestInterceptor, + BackupDrProtectionSummaryRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[BackupDrProtectionSummaryTransport]] +_transport_registry["grpc"] = BackupDrProtectionSummaryGrpcTransport +_transport_registry["grpc_asyncio"] = BackupDrProtectionSummaryGrpcAsyncIOTransport +_transport_registry["rest"] = BackupDrProtectionSummaryRestTransport + +__all__ = ( + "BackupDrProtectionSummaryTransport", + "BackupDrProtectionSummaryGrpcTransport", + "BackupDrProtectionSummaryGrpcAsyncIOTransport", + "BackupDrProtectionSummaryRestTransport", + "BackupDrProtectionSummaryRestInterceptor", +) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/base.py new file mode 100644 index 000000000000..20f692f9c8ef --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/base.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.backupdr_v1beta import gapic_version as package_version +from google.cloud.backupdr_v1beta.types import protection_summary + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class BackupDrProtectionSummaryTransport(abc.ABC): + """Abstract transport class for BackupDrProtectionSummary.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "backupdr.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_resource_backup_configs: gapic_v1.method.wrap_method( + self.list_resource_backup_configs, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_resource_backup_configs( + self, + ) -> Callable[ + [protection_summary.ListResourceBackupConfigsRequest], + Union[ + protection_summary.ListResourceBackupConfigsResponse, + Awaitable[protection_summary.ListResourceBackupConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("BackupDrProtectionSummaryTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/grpc.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/grpc.py new file mode 100644 index 000000000000..190c90406293 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/grpc.py @@ -0,0 +1,559 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.backupdr_v1beta.types import protection_summary + +from .base import DEFAULT_CLIENT_INFO, BackupDrProtectionSummaryTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BackupDrProtectionSummaryGrpcTransport(BackupDrProtectionSummaryTransport): + """gRPC backend transport for BackupDrProtectionSummary. + + The Protection Summary service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_resource_backup_configs( + self, + ) -> Callable[ + [protection_summary.ListResourceBackupConfigsRequest], + protection_summary.ListResourceBackupConfigsResponse, + ]: + r"""Return a callable for the list resource backup configs method over gRPC. + + Lists ResourceBackupConfigs. + + Returns: + Callable[[~.ListResourceBackupConfigsRequest], + ~.ListResourceBackupConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_resource_backup_configs" not in self._stubs: + self._stubs["list_resource_backup_configs"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDrProtectionSummary/ListResourceBackupConfigs", + request_serializer=protection_summary.ListResourceBackupConfigsRequest.serialize, + response_deserializer=protection_summary.ListResourceBackupConfigsResponse.deserialize, + ) + ) + return self._stubs["list_resource_backup_configs"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("BackupDrProtectionSummaryGrpcTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/grpc_asyncio.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/grpc_asyncio.py new file mode 100644 index 000000000000..54474597f0e2 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/grpc_asyncio.py @@ -0,0 +1,636 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.backupdr_v1beta.types import protection_summary + +from .base import DEFAULT_CLIENT_INFO, BackupDrProtectionSummaryTransport +from .grpc import BackupDrProtectionSummaryGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BackupDrProtectionSummaryGrpcAsyncIOTransport(BackupDrProtectionSummaryTransport): + """gRPC AsyncIO backend transport for BackupDrProtectionSummary. + + The Protection Summary service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_resource_backup_configs( + self, + ) -> Callable[ + [protection_summary.ListResourceBackupConfigsRequest], + Awaitable[protection_summary.ListResourceBackupConfigsResponse], + ]: + r"""Return a callable for the list resource backup configs method over gRPC. + + Lists ResourceBackupConfigs. + + Returns: + Callable[[~.ListResourceBackupConfigsRequest], + Awaitable[~.ListResourceBackupConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_resource_backup_configs" not in self._stubs: + self._stubs["list_resource_backup_configs"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDrProtectionSummary/ListResourceBackupConfigs", + request_serializer=protection_summary.ListResourceBackupConfigsRequest.serialize, + response_deserializer=protection_summary.ListResourceBackupConfigsResponse.deserialize, + ) + ) + return self._stubs["list_resource_backup_configs"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_resource_backup_configs: self._wrap_method( + self.list_resource_backup_configs, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("BackupDrProtectionSummaryGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/rest.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/rest.py new file mode 100644 index 000000000000..e7cad4a80830 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/rest.py @@ -0,0 +1,1870 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.backupdr_v1beta._compat import transcode_request +from google.cloud.backupdr_v1beta.types import protection_summary + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseBackupDrProtectionSummaryRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class BackupDrProtectionSummaryRestInterceptor: + """Interceptor for BackupDrProtectionSummary. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the BackupDrProtectionSummaryRestTransport. + + .. code-block:: python + class MyCustomBackupDrProtectionSummaryInterceptor(BackupDrProtectionSummaryRestInterceptor): + def pre_list_resource_backup_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_backup_configs(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BackupDrProtectionSummaryRestTransport(interceptor=MyCustomBackupDrProtectionSummaryInterceptor()) + client = BackupDrProtectionSummaryClient(transport=transport) + + + """ + + def pre_list_resource_backup_configs( + self, + request: protection_summary.ListResourceBackupConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + protection_summary.ListResourceBackupConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_resource_backup_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_list_resource_backup_configs( + self, response: protection_summary.ListResourceBackupConfigsResponse + ) -> protection_summary.ListResourceBackupConfigsResponse: + """Post-rpc interceptor for list_resource_backup_configs + + DEPRECATED. Please use the `post_list_resource_backup_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. This `post_list_resource_backup_configs` interceptor runs + before the `post_list_resource_backup_configs_with_metadata` interceptor. + """ + return response + + def post_list_resource_backup_configs_with_metadata( + self, + response: protection_summary.ListResourceBackupConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + protection_summary.ListResourceBackupConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_resource_backup_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDrProtectionSummary server but before it is returned to user code. + + We recommend only using this `post_list_resource_backup_configs_with_metadata` + interceptor in new development instead of the `post_list_resource_backup_configs` interceptor. + When both interceptors are used, this `post_list_resource_backup_configs_with_metadata` interceptor runs after the + `post_list_resource_backup_configs` interceptor. The (possibly modified) response returned by + `post_list_resource_backup_configs` will be passed to + `post_list_resource_backup_configs_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDrProtectionSummary server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the BackupDrProtectionSummary server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BackupDrProtectionSummaryRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BackupDrProtectionSummaryRestInterceptor + + +class BackupDrProtectionSummaryRestTransport( + _BaseBackupDrProtectionSummaryRestTransport +): + """REST backend synchronous transport for BackupDrProtectionSummary. + + The Protection Summary service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[BackupDrProtectionSummaryRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[BackupDrProtectionSummaryRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or BackupDrProtectionSummaryRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListResourceBackupConfigs( + _BaseBackupDrProtectionSummaryRestTransport._BaseListResourceBackupConfigs, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash( + "BackupDrProtectionSummaryRestTransport.ListResourceBackupConfigs" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: protection_summary.ListResourceBackupConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> protection_summary.ListResourceBackupConfigsResponse: + r"""Call the list resource backup + configs method over HTTP. + + Args: + request (~.protection_summary.ListResourceBackupConfigsRequest): + The request object. Request for + ListResourceBackupConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.protection_summary.ListResourceBackupConfigsResponse: + Response for + ListResourceBackupConfigs. + + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseListResourceBackupConfigs._get_http_options() + request, metadata = self._interceptor.pre_list_resource_backup_configs( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseListResourceBackupConfigs, + "_BaseListResourceBackupConfigs__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.ListResourceBackupConfigs", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "ListResourceBackupConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDrProtectionSummaryRestTransport._ListResourceBackupConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = protection_summary.ListResourceBackupConfigsResponse() + pb_resp = protection_summary.ListResourceBackupConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_resource_backup_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_resource_backup_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + protection_summary.ListResourceBackupConfigsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.list_resource_backup_configs", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "ListResourceBackupConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def list_resource_backup_configs( + self, + ) -> Callable[ + [protection_summary.ListResourceBackupConfigsRequest], + protection_summary.ListResourceBackupConfigsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListResourceBackupConfigs( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseBackupDrProtectionSummaryRestTransport._BaseGetLocation, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.GetLocation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseBackupDrProtectionSummaryRestTransport._BaseListLocations, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.ListLocations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseBackupDrProtectionSummaryRestTransport._BaseGetIamPolicy, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseBackupDrProtectionSummaryRestTransport._BaseSetIamPolicy, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseBackupDrProtectionSummaryRestTransport._BaseTestIamPermissions, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseTestIamPermissions, + "_BaseTestIamPermissions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDrProtectionSummaryRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseBackupDrProtectionSummaryRestTransport._BaseCancelOperation, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.CancelOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseBackupDrProtectionSummaryRestTransport._BaseDeleteOperation, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseDeleteOperation, + "_BaseDeleteOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseBackupDrProtectionSummaryRestTransport._BaseGetOperation, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.GetOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseBackupDrProtectionSummaryRestTransport._BaseListOperations, + BackupDrProtectionSummaryRestStub, + ): + def __hash__(self): + return hash("BackupDrProtectionSummaryRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseBackupDrProtectionSummaryRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDrProtectionSummaryRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.ListOperations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDrProtectionSummaryRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("BackupDrProtectionSummaryRestTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/rest_base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/rest_base.py new file mode 100644 index 000000000000..a7017e1fd9de --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr_protection_summary/transports/rest_base.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.backupdr_v1beta.types import protection_summary + +from .base import DEFAULT_CLIENT_INFO, BackupDrProtectionSummaryTransport + + +class _BaseBackupDrProtectionSummaryRestTransport(BackupDrProtectionSummaryTransport): + """Base REST backend transport for BackupDrProtectionSummary. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "backupdr.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseListResourceBackupConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/resourceBackupConfigs", + }, + ] + return http_options + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{resource=projects/*/locations/*/managementServers/*}:getIamPolicy", + }, + ] + return http_options + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{resource=projects/*/locations/*/managementServers/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{resource=projects/*/locations/*/managementServers/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseBackupDrProtectionSummaryRestTransport",) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/__init__.py new file mode 100644 index 000000000000..f5c59a6ebe29 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/__init__.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .appliedautoprotectionpolicy import ( + AppliedAutoProtectionPolicy, + ListAppliedAutoProtectionPoliciesRequest, + ListAppliedAutoProtectionPoliciesResponse, +) +from .autoprotectionpolicy import ( + AutoProtectionPolicy, + BackupPlanDetail, + BindingSummary, + CreateAutoProtectionPolicyRequest, + Criteria, + DeleteAutoProtectionPolicyRequest, + GetAutoProtectionPolicyRequest, + KeyValuePair, + ListAutoProtectionPoliciesRequest, + ListAutoProtectionPoliciesResponse, + MatchingCondition, + PolicyEvaluationSummary, + UpdateAutoProtectionPolicyRequest, +) +from .autoprotectionpolicybinding import ( + AutoProtectionPolicyBinding, + BindingEvaluationSummary, + CreateAutoProtectionPolicyBindingRequest, + GetAutoProtectionPolicyBindingRequest, + InitiateDeleteAutoProtectionPolicyBindingRequest, + ListAutoProtectionPolicyBindingsRequest, + ListAutoProtectionPolicyBindingsResponse, +) +from .backupdr import ( + CreateManagementServerRequest, + DeleteManagementServerRequest, + GetManagementServerRequest, + InitializeServiceRequest, + InitializeServiceResponse, + ListManagementServersRequest, + ListManagementServersResponse, + ManagementServer, + ManagementURI, + NetworkConfig, + OperationMetadata, + WorkforceIdentityBasedManagementURI, + WorkforceIdentityBasedOAuth2ClientID, +) +from .backupplan import ( + BackupPlan, + BackupPlanRevision, + BackupRule, + BackupWindow, + ComputeInstanceBackupPlanProperties, + CreateBackupPlanRequest, + DeleteBackupPlanRequest, + DiskBackupPlanProperties, + GetBackupPlanRequest, + GetBackupPlanRevisionRequest, + ListBackupPlanRevisionsRequest, + ListBackupPlanRevisionsResponse, + ListBackupPlansRequest, + ListBackupPlansResponse, + StandardSchedule, + UpdateBackupPlanRequest, + WeekDayOfMonth, +) +from .backupplanassociation import ( + BackupPlanAssociation, + CreateBackupPlanAssociationRequest, + DeleteBackupPlanAssociationRequest, + FetchBackupPlanAssociationsForResourceTypeRequest, + FetchBackupPlanAssociationsForResourceTypeResponse, + GetBackupPlanAssociationRequest, + ListBackupPlanAssociationsRequest, + ListBackupPlanAssociationsResponse, + RuleConfigInfo, + TriggerBackupRequest, + UpdateBackupPlanAssociationRequest, +) +from .backupvault import ( + Backup, + BackupApplianceBackupConfig, + BackupApplianceLockInfo, + BackupConfigInfo, + BackupConfigState, + BackupGcpResource, + BackupLock, + BackupVault, + BackupVaultView, + BackupView, + CreateBackupVaultRequest, + DataSource, + DataSourceBackupApplianceApplication, + DataSourceGcpResource, + DeleteBackupRequest, + DeleteBackupVaultRequest, + FetchBackupsForResourceTypeRequest, + FetchBackupsForResourceTypeResponse, + FetchUsableBackupVaultsRequest, + FetchUsableBackupVaultsResponse, + GcpBackupConfig, + GcpResource, + GetBackupRequest, + GetBackupVaultRequest, + GetDataSourceRequest, + ListBackupsRequest, + ListBackupsResponse, + ListBackupVaultsRequest, + ListBackupVaultsResponse, + ListDataSourcesRequest, + ListDataSourcesResponse, + RestoreBackupRequest, + RestoreBackupResponse, + ServiceLockInfo, + TargetResource, + UpdateBackupRequest, + UpdateBackupVaultRequest, + UpdateDataSourceRequest, +) +from .backupvault_alloydb import ( + AlloyDBClusterBackupPlanAssociationProperties, + AlloyDbClusterBackupProperties, + AlloyDBClusterDataSourceProperties, + AlloyDBClusterDataSourceReferenceProperties, + AlloyDbPitrWindow, +) +from .backupvault_ba import ( + BackupApplianceBackupProperties, +) +from .backupvault_cloudsql import ( + CloudSqlInstanceBackupPlanAssociationProperties, + CloudSqlInstanceBackupProperties, + CloudSqlInstanceDataSourceProperties, + CloudSqlInstanceDataSourceReferenceProperties, + CloudSqlInstanceInitializationConfig, +) +from .backupvault_disk import ( + DiskBackupProperties, + DiskDataSourceProperties, + DiskRestoreProperties, + DiskTargetEnvironment, + RegionDiskTargetEnvironment, + RestoreDiskFromInstanceOptions, +) +from .backupvault_gce import ( + AcceleratorConfig, + AccessConfig, + AdvancedMachineFeatures, + AliasIpRange, + AllocationAffinity, + AttachedDisk, + ComputeInstanceBackupProperties, + ComputeInstanceDataSourceProperties, + ComputeInstanceRestoreProperties, + ComputeInstanceTargetEnvironment, + ConfidentialInstanceConfig, + CustomerEncryptionKey, + DisplayDevice, + Entry, + GuestOsFeature, + InstanceParams, + KeyRevocationActionType, + Metadata, + NetworkInterface, + NetworkPerformanceConfig, + Scheduling, + SchedulingDuration, + ServiceAccount, + Tags, +) +from .bindingmatchingresource import ( + AutoProtectionDetails, + BindingMatchingResource, + GetBindingMatchingResourceRequest, + ListBindingMatchingResourcesRequest, + ListBindingMatchingResourcesResponse, +) +from .datasourcereference import ( + DataSourceBackupConfigInfo, + DataSourceGcpResourceInfo, + DataSourceReference, + FetchDataSourceReferencesForResourceTypeRequest, + FetchDataSourceReferencesForResourceTypeResponse, + GetDataSourceReferenceRequest, + ListDataSourceReferencesRequest, + ListDataSourceReferencesResponse, +) +from .protection_summary import ( + BackupConfigDetails, + BackupDrPlanConfig, + BackupDrPlanRule, + BackupDrTemplateConfig, + BackupLocation, + ListResourceBackupConfigsRequest, + ListResourceBackupConfigsResponse, + PitrSettings, + ResourceBackupConfig, +) + +__all__ = ( + "AppliedAutoProtectionPolicy", + "ListAppliedAutoProtectionPoliciesRequest", + "ListAppliedAutoProtectionPoliciesResponse", + "AutoProtectionPolicy", + "BackupPlanDetail", + "BindingSummary", + "CreateAutoProtectionPolicyRequest", + "Criteria", + "DeleteAutoProtectionPolicyRequest", + "GetAutoProtectionPolicyRequest", + "KeyValuePair", + "ListAutoProtectionPoliciesRequest", + "ListAutoProtectionPoliciesResponse", + "MatchingCondition", + "PolicyEvaluationSummary", + "UpdateAutoProtectionPolicyRequest", + "AutoProtectionPolicyBinding", + "BindingEvaluationSummary", + "CreateAutoProtectionPolicyBindingRequest", + "GetAutoProtectionPolicyBindingRequest", + "InitiateDeleteAutoProtectionPolicyBindingRequest", + "ListAutoProtectionPolicyBindingsRequest", + "ListAutoProtectionPolicyBindingsResponse", + "CreateManagementServerRequest", + "DeleteManagementServerRequest", + "GetManagementServerRequest", + "InitializeServiceRequest", + "InitializeServiceResponse", + "ListManagementServersRequest", + "ListManagementServersResponse", + "ManagementServer", + "ManagementURI", + "NetworkConfig", + "OperationMetadata", + "WorkforceIdentityBasedManagementURI", + "WorkforceIdentityBasedOAuth2ClientID", + "BackupPlan", + "BackupPlanRevision", + "BackupRule", + "BackupWindow", + "ComputeInstanceBackupPlanProperties", + "CreateBackupPlanRequest", + "DeleteBackupPlanRequest", + "DiskBackupPlanProperties", + "GetBackupPlanRequest", + "GetBackupPlanRevisionRequest", + "ListBackupPlanRevisionsRequest", + "ListBackupPlanRevisionsResponse", + "ListBackupPlansRequest", + "ListBackupPlansResponse", + "StandardSchedule", + "UpdateBackupPlanRequest", + "WeekDayOfMonth", + "BackupPlanAssociation", + "CreateBackupPlanAssociationRequest", + "DeleteBackupPlanAssociationRequest", + "FetchBackupPlanAssociationsForResourceTypeRequest", + "FetchBackupPlanAssociationsForResourceTypeResponse", + "GetBackupPlanAssociationRequest", + "ListBackupPlanAssociationsRequest", + "ListBackupPlanAssociationsResponse", + "RuleConfigInfo", + "TriggerBackupRequest", + "UpdateBackupPlanAssociationRequest", + "Backup", + "BackupApplianceBackupConfig", + "BackupApplianceLockInfo", + "BackupConfigInfo", + "BackupGcpResource", + "BackupLock", + "BackupVault", + "CreateBackupVaultRequest", + "DataSource", + "DataSourceBackupApplianceApplication", + "DataSourceGcpResource", + "DeleteBackupRequest", + "DeleteBackupVaultRequest", + "FetchBackupsForResourceTypeRequest", + "FetchBackupsForResourceTypeResponse", + "FetchUsableBackupVaultsRequest", + "FetchUsableBackupVaultsResponse", + "GcpBackupConfig", + "GcpResource", + "GetBackupRequest", + "GetBackupVaultRequest", + "GetDataSourceRequest", + "ListBackupsRequest", + "ListBackupsResponse", + "ListBackupVaultsRequest", + "ListBackupVaultsResponse", + "ListDataSourcesRequest", + "ListDataSourcesResponse", + "RestoreBackupRequest", + "RestoreBackupResponse", + "ServiceLockInfo", + "TargetResource", + "UpdateBackupRequest", + "UpdateBackupVaultRequest", + "UpdateDataSourceRequest", + "BackupConfigState", + "BackupVaultView", + "BackupView", + "AlloyDBClusterBackupPlanAssociationProperties", + "AlloyDbClusterBackupProperties", + "AlloyDBClusterDataSourceProperties", + "AlloyDBClusterDataSourceReferenceProperties", + "AlloyDbPitrWindow", + "BackupApplianceBackupProperties", + "CloudSqlInstanceBackupPlanAssociationProperties", + "CloudSqlInstanceBackupProperties", + "CloudSqlInstanceDataSourceProperties", + "CloudSqlInstanceDataSourceReferenceProperties", + "CloudSqlInstanceInitializationConfig", + "DiskBackupProperties", + "DiskDataSourceProperties", + "DiskRestoreProperties", + "DiskTargetEnvironment", + "RegionDiskTargetEnvironment", + "RestoreDiskFromInstanceOptions", + "AcceleratorConfig", + "AccessConfig", + "AdvancedMachineFeatures", + "AliasIpRange", + "AllocationAffinity", + "AttachedDisk", + "ComputeInstanceBackupProperties", + "ComputeInstanceDataSourceProperties", + "ComputeInstanceRestoreProperties", + "ComputeInstanceTargetEnvironment", + "ConfidentialInstanceConfig", + "CustomerEncryptionKey", + "DisplayDevice", + "Entry", + "GuestOsFeature", + "InstanceParams", + "Metadata", + "NetworkInterface", + "NetworkPerformanceConfig", + "Scheduling", + "SchedulingDuration", + "ServiceAccount", + "Tags", + "KeyRevocationActionType", + "AutoProtectionDetails", + "BindingMatchingResource", + "GetBindingMatchingResourceRequest", + "ListBindingMatchingResourcesRequest", + "ListBindingMatchingResourcesResponse", + "DataSourceBackupConfigInfo", + "DataSourceGcpResourceInfo", + "DataSourceReference", + "FetchDataSourceReferencesForResourceTypeRequest", + "FetchDataSourceReferencesForResourceTypeResponse", + "GetDataSourceReferenceRequest", + "ListDataSourceReferencesRequest", + "ListDataSourceReferencesResponse", + "BackupConfigDetails", + "BackupDrPlanConfig", + "BackupDrPlanRule", + "BackupDrTemplateConfig", + "BackupLocation", + "ListResourceBackupConfigsRequest", + "ListResourceBackupConfigsResponse", + "PitrSettings", + "ResourceBackupConfig", +) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/appliedautoprotectionpolicy.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/appliedautoprotectionpolicy.py new file mode 100644 index 000000000000..68de8c056b9c --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/appliedautoprotectionpolicy.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1beta.types import ( + autoprotectionpolicy, + autoprotectionpolicybinding, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "AppliedAutoProtectionPolicy", + "ListAppliedAutoProtectionPoliciesRequest", + "ListAppliedAutoProtectionPoliciesResponse", + }, +) + + +class AppliedAutoProtectionPolicy(proto.Message): + r"""AppliedAutoProtectionPolicy is a read-only view of + AutoProtectionPolicy and AutoProtectionPolicyBinding resources + that apply to a given workload project. + + Attributes: + name (str): + Identifier. Canonical resource name. + Format: + + projects/{workload-project-number}/locations/{location}/appliedAutoProtectionPolicies/{id}. + source_binding (str): + Output only. The full resource name of the + AutoProtectionPolicyBinding that applies the source policy + to a scope including this workload project. e.g., + projects/{admin-project}/locations/{location}/autoProtectionPolicies/{policy_id}/autoProtectionPolicyBindings/{binding_id}. + criteria (google.cloud.backupdr_v1beta.types.Criteria): + Output only. The criteria resources must meet + for this rule to apply. From + AutoProtectionPolicy.criteria. + backup_plan_details (MutableSequence[google.cloud.backupdr_v1beta.types.BackupPlanDetail]): + Output only. The set of backup plan configurations, + mirroring the backup_plan_details from the source + AutoProtectionPolicy. Each element specifies a backup plan + for a given resource type. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp indicating when the + binding was last modified. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp indicating when the + binding was last created. + binding_evaluation_summary (google.cloud.backupdr_v1beta.types.BindingEvaluationSummary): + Output only. The summary of the last policy + application when the job has run. + status (google.cloud.backupdr_v1beta.types.AppliedAutoProtectionPolicy.State): + Output only. The status of the applied auto + protection policy. + """ + + class State(proto.Enum): + r"""Represents the various states an applied auto protection + policy can be in. + + Values: + STATE_UNSPECIFIED (0): + State is not specified. + CREATING (1): + The policy is in the process of being + applied. + ACTIVE (2): + The policy has been applied and is active. + DELETION_INITIATED (3): + The policy is in the process of being + removed. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETION_INITIATED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + source_binding: str = proto.Field( + proto.STRING, + number=2, + ) + criteria: autoprotectionpolicy.Criteria = proto.Field( + proto.MESSAGE, + number=3, + message=autoprotectionpolicy.Criteria, + ) + backup_plan_details: MutableSequence[autoprotectionpolicy.BackupPlanDetail] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message=autoprotectionpolicy.BackupPlanDetail, + ) + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + binding_evaluation_summary: autoprotectionpolicybinding.BindingEvaluationSummary = ( + proto.Field( + proto.MESSAGE, + number=7, + message=autoprotectionpolicybinding.BindingEvaluationSummary, + ) + ) + status: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + + +class ListAppliedAutoProtectionPoliciesRequest(proto.Message): + r"""Request message for listing AppliedAutoProtectionPolicies. + + Attributes: + parent (str): + Required. The project and location for which + to retrieve the list of applied policies. + Format: projects/{project}/locations/{location} + page_size (int): + Optional. The maximum number of applied + policies to return in a single page. + page_token (str): + Optional. A page token, received from a previous + ``ListAppliedAutoProtectionPolicies`` call. + filter (str): + Optional. A filter expression that filters + resources listed in the response. + order_by (str): + Optional. An expression that sorts the + results in the response. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAppliedAutoProtectionPoliciesResponse(proto.Message): + r"""Response message for ListAppliedAutoProtectionPolicies. + + Attributes: + applied_auto_protection_policies (MutableSequence[google.cloud.backupdr_v1beta.types.AppliedAutoProtectionPolicy]): + A list of the AppliedAutoProtectionPolicy + resources found. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. + unreachable (MutableSequence[str]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + applied_auto_protection_policies: MutableSequence["AppliedAutoProtectionPolicy"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AppliedAutoProtectionPolicy", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicy.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicy.py new file mode 100644 index 000000000000..562884def56c --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicy.py @@ -0,0 +1,482 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "AutoProtectionPolicy", + "BackupPlanDetail", + "Criteria", + "MatchingCondition", + "PolicyEvaluationSummary", + "BindingSummary", + "KeyValuePair", + "CreateAutoProtectionPolicyRequest", + "GetAutoProtectionPolicyRequest", + "UpdateAutoProtectionPolicyRequest", + "DeleteAutoProtectionPolicyRequest", + "ListAutoProtectionPoliciesRequest", + "ListAutoProtectionPoliciesResponse", + }, +) + + +class AutoProtectionPolicy(proto.Message): + r"""An AutoprotectionPolicy is a policy resource designed to + automate backup management, moving from manual per-resource + protection to a bulk approach. The policy dynamically discovers + and applies a specified backup plan to all eligible resources + that match its defined scope and criteria. + + Attributes: + name (str): + Identifier. The resource name of the AutoprotectionPolicy. + Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}`` + description (str): + Optional. A description of the policy. + backup_plan_details (MutableSequence[google.cloud.backupdr_v1beta.types.BackupPlanDetail]): + Required. The backup plan details for + matching resources. + criteria (google.cloud.backupdr_v1beta.types.Criteria): + Required. The criteria for matching + resources. + state (google.cloud.backupdr_v1beta.types.AutoProtectionPolicy.State): + Output only. The current state of the + AutoprotectionPolicy. + etag (str): + Output only. The etag for the policy. + If this is provided on update, it must match the + server's etag, otherwise the request will be + rejected with an ABORTED error. + binding_summary (google.cloud.backupdr_v1beta.types.BindingSummary): + Output only. Summary of total count of + different containers covered through this + policy. + policy_evaluation_summary (google.cloud.backupdr_v1beta.types.PolicyEvaluationSummary): + Output only. Summary of last policy + application when job was run per workload type. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the policy + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the policy + was last updated. + """ + + class State(proto.Enum): + r"""The state of an AutoprotectionPolicy. + + Values: + STATE_UNSPECIFIED (0): + The state of the policy is unspecified. + CREATING (1): + The policy is being created. + ACTIVE (2): + The policy is active and protecting matching + resources. + UPDATING (3): + The policy is being updated. + DELETING (4): + The policy is being deleted. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + backup_plan_details: MutableSequence["BackupPlanDetail"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="BackupPlanDetail", + ) + criteria: "Criteria" = proto.Field( + proto.MESSAGE, + number=4, + message="Criteria", + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + binding_summary: "BindingSummary" = proto.Field( + proto.MESSAGE, + number=7, + message="BindingSummary", + ) + policy_evaluation_summary: "PolicyEvaluationSummary" = proto.Field( + proto.MESSAGE, + number=8, + message="PolicyEvaluationSummary", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class BackupPlanDetail(proto.Message): + r"""BackupPlanDetail defines configuration of protection. + + Attributes: + resource_type (str): + Required. The type of resource that this policy will + automatically protect. For MVP, + ``compute.googleapis.com/Instance`` and + ``compute.googleapis.com/Disk`` are supported. + backup_plan (str): + Required. The resource name of the BackupPlan + to apply to resources that match the policy's + criteria. This backup plan must be in the same + location as AutoProtectionPolicy. Format: + + projects/{project}/locations/{location}/backupPlans/{backupPlanId} + """ + + resource_type: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Criteria(proto.Message): + r"""Criteria specifies a set of criteria for matching resources. + + Attributes: + matching_conditions (MutableSequence[google.cloud.backupdr_v1beta.types.MatchingCondition]): + Required. A list of matching conditions that + a resource must meet to be protected by the + policy. + """ + + matching_conditions: MutableSequence["MatchingCondition"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="MatchingCondition", + ) + + +class MatchingCondition(proto.Message): + r"""MatchingCondition specifies a set of conditions for matching + resources. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + label_condition (google.cloud.backupdr_v1beta.types.KeyValuePair): + Optional. A condition that matches resources + based on their labels. For MVP, this is limited + to a single label match. + + This field is a member of `oneof`_ ``condition``. + """ + + label_condition: "KeyValuePair" = proto.Field( + proto.MESSAGE, + number=1, + oneof="condition", + message="KeyValuePair", + ) + + +class PolicyEvaluationSummary(proto.Message): + r"""PolicyEvaluationSummary contains the summary of the last run + of job that applies policy to matching resources. + + Attributes: + matching_resource_count (int): + Output only. The number of resources that + currently match the policy's criteria. + protected_resource_count (int): + Output only. The number of matching resources + that are successfully protected. + failed_resource_count (int): + Output only. The number of matching resources + whose protection failed during job run. + """ + + matching_resource_count: int = proto.Field( + proto.INT64, + number=1, + ) + protected_resource_count: int = proto.Field( + proto.INT64, + number=2, + ) + failed_resource_count: int = proto.Field( + proto.INT64, + number=3, + ) + + +class BindingSummary(proto.Message): + r"""BindingSummary contains count of different containers covered + through this policy. + + Attributes: + project_count (int): + Output only. Total count of Projects + protected with this policy. + """ + + project_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class KeyValuePair(proto.Message): + r"""KeyValuePair defines a key-value pair for matching resource + labels. + + Attributes: + key (str): + Required. The key of the label to match. This must be in the + format ``{label_key}``. The key must match the regex + Format:``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. + values (MutableSequence[str]): + Required. The values of the label to match. There will be + explicit “OR” between values of array. Each value must be in + the format ``{label_value}``. The value must match the regex + Format: ``[\\p{Ll}\\p{Lo}\\p{N}_-]{1,63}``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CreateAutoProtectionPolicyRequest(proto.Message): + r"""Request message for creating an AutoProtectionPolicy. + + Attributes: + parent (str): + Required. The parent resource where this + policy will be created. Format: + projects/{project}/locations/{location} + auto_protection_policy_id (str): + Required. The ID to use for the policy. + This will become the final component of the + policy's resource name. + auto_protection_policy (google.cloud.backupdr_v1beta.types.AutoProtectionPolicy): + Required. The AutoProtectionPolicy resource + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + auto_protection_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + auto_protection_policy: "AutoProtectionPolicy" = proto.Field( + proto.MESSAGE, + number=3, + message="AutoProtectionPolicy", + ) + + +class GetAutoProtectionPolicyRequest(proto.Message): + r"""Request message for getting an AutoProtectionPolicy. + + Attributes: + name (str): + Required. The name of the policy to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAutoProtectionPolicyRequest(proto.Message): + r"""Request message for updating an AutoProtectionPolicy. + + Attributes: + auto_protection_policy (google.cloud.backupdr_v1beta.types.AutoProtectionPolicy): + Required. The policy to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the AutoProtectionPolicy resource by the + update. The fields specified in the update_mask are relative + to the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + """ + + auto_protection_policy: "AutoProtectionPolicy" = proto.Field( + proto.MESSAGE, + number=1, + message="AutoProtectionPolicy", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAutoProtectionPolicyRequest(proto.Message): + r"""Request message for deleting an AutoProtectionPolicy. + + Attributes: + name (str): + Required. The name of the policy to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + etag (str): + The current etag of the AutoProtectionPolicy. + If an etag is provided and does not match the + current etag of the connection, the request will + be rejected with an ABORTED error. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAutoProtectionPoliciesRequest(proto.Message): + r"""Request message for ListAutoProtectionPolicies. + + Attributes: + parent (str): + Required. The project and location for which + to retrieve the list of policies. Format: + projects/{project}/locations/{location} + page_size (int): + Optional. The maximum number of policies to + return in a single page. If unspecified, a + server-default value will be used. + page_token (str): + Optional. A page token, received from a previous + ``ListAutoProtectionPolicies`` call. Provide this to + retrieve the subsequent page. + filter (str): + Optional. A filter expression that filters + resources listed in the response. The following + fields are filterable: + order_by (str): + Optional. An expression that sorts the + results in the response. The following fields + are sortable: + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAutoProtectionPoliciesResponse(proto.Message): + r"""Response message for ListAutoProtectionPolicies. + + Attributes: + auto_protection_policies (MutableSequence[google.cloud.backupdr_v1beta.types.AutoProtectionPolicy]): + A list of the AutoProtectionPolicy resources + found. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + auto_protection_policies: MutableSequence["AutoProtectionPolicy"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AutoProtectionPolicy", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicybinding.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicybinding.py new file mode 100644 index 000000000000..f0c5c3900a71 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicybinding.py @@ -0,0 +1,308 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "AutoProtectionPolicyBinding", + "BindingEvaluationSummary", + "CreateAutoProtectionPolicyBindingRequest", + "GetAutoProtectionPolicyBindingRequest", + "ListAutoProtectionPolicyBindingsRequest", + "ListAutoProtectionPolicyBindingsResponse", + "InitiateDeleteAutoProtectionPolicyBindingRequest", + }, +) + + +class AutoProtectionPolicyBinding(proto.Message): + r"""An AutoprotectionPolicyBinding (APPA) acts as the bridge + between an AutoprotectionPolicy and the scope (Project, Folder, + or Organization) where the policy should be applied. + + Attributes: + name (str): + Identifier. The resource name of the + AutoProtectionPolicyBinding. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}`` + description (str): + Optional. A description of the binding. + state (google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding.State): + Output only. The current state of the + AutoProtectionPolicyBinding. + scope (str): + Required. Immutable. Resource Id of target container on + which policy will be applied. Format: projects/{project_id} + binding_evaluation_summary (google.cloud.backupdr_v1beta.types.BindingEvaluationSummary): + Output only. Summaries of the last policy + application when the job has run, with one entry + per resource type specified in the + AutoProtectionPolicy. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the binding + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the binding + was last updated. + etag (str): + Optional. Output only. The etag for the + binding. If this is provided on update, it must + match the server's etag. + """ + + class State(proto.Enum): + r"""The state of an AutoProtectionPolicyBinding. + + Values: + STATE_UNSPECIFIED (0): + The state of the binding is unspecified. + CREATING (1): + The binding is being created. + ACTIVE (2): + The binding is active. + DELETION_INITIATED (3): + The binding deletion is initiated. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETION_INITIATED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + scope: str = proto.Field( + proto.STRING, + number=4, + ) + binding_evaluation_summary: "BindingEvaluationSummary" = proto.Field( + proto.MESSAGE, + number=5, + message="BindingEvaluationSummary", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=8, + ) + + +class BindingEvaluationSummary(proto.Message): + r"""BindingEvaluationSummary contains the summary of the last run + of job that applies policy to matching resources for a given + binding. + + Attributes: + matching_resource_count (int): + Output only. The number of resources that + currently match the policy's criteria. + protected_resource_count (int): + Output only. The number of matching resources + that are successfully protected. + failed_resource_count (int): + Output only. The number of matching resources + whose protection failed during job run. + """ + + matching_resource_count: int = proto.Field( + proto.INT64, + number=1, + ) + protected_resource_count: int = proto.Field( + proto.INT64, + number=2, + ) + failed_resource_count: int = proto.Field( + proto.INT64, + number=3, + ) + + +class CreateAutoProtectionPolicyBindingRequest(proto.Message): + r"""Request message for creating an AutoProtectionPolicyBinding. + + Attributes: + parent (str): + Required. The parent resource where this binding will be + created. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + auto_protection_policy_binding_id (str): + Required. The ID to use for the binding. + This will become the final component of the + binding's resource name. + auto_protection_policy_binding (google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding): + Required. The AutoProtectionPolicyBinding + resource to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + auto_protection_policy_binding_id: str = proto.Field( + proto.STRING, + number=2, + ) + auto_protection_policy_binding: "AutoProtectionPolicyBinding" = proto.Field( + proto.MESSAGE, + number=3, + message="AutoProtectionPolicyBinding", + ) + + +class GetAutoProtectionPolicyBindingRequest(proto.Message): + r"""Request message for getting an AutoProtectionPolicyBinding. + + Attributes: + name (str): + Required. The name of the binding to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAutoProtectionPolicyBindingsRequest(proto.Message): + r"""Request message for ListAutoProtectionPolicyBindings. + + Attributes: + parent (str): + Required. The project and location for which + to retrieve the list of policies. Format: + projects/{project}/locations/{location} + page_size (int): + Optional. The maximum number of policies to + return in a single page. If unspecified, a + server-default value will be used. + page_token (str): + Optional. A page token, received from a previous + ``ListAutoProtectionPolicies`` call. Provide this to + retrieve the subsequent page. + filter (str): + Optional. A filter expression that filters + resources listed in the response. The following + fields are filterable: + order_by (str): + Optional. An expression that sorts the + results in the response. The following fields + are sortable: + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAutoProtectionPolicyBindingsResponse(proto.Message): + r"""Response message for ListAutoProtectionPolicyBindings. + + Attributes: + auto_protection_policy_bindings (MutableSequence[google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding]): + A list of the AutoProtectionPolicyBindings + resources found. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + auto_protection_policy_bindings: MutableSequence["AutoProtectionPolicyBinding"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AutoProtectionPolicyBinding", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class InitiateDeleteAutoProtectionPolicyBindingRequest(proto.Message): + r"""Request message for initiating delete of an + AutoProtectionPolicyBinding. + + Attributes: + name (str): + Required. The name of the binding to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupdr.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupdr.py new file mode 100644 index 000000000000..56114bf0c8a6 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupdr.py @@ -0,0 +1,743 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1beta.types import backupvault_cloudsql + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "NetworkConfig", + "ManagementURI", + "WorkforceIdentityBasedManagementURI", + "WorkforceIdentityBasedOAuth2ClientID", + "ManagementServer", + "ListManagementServersRequest", + "ListManagementServersResponse", + "GetManagementServerRequest", + "CreateManagementServerRequest", + "DeleteManagementServerRequest", + "InitializeServiceRequest", + "InitializeServiceResponse", + "OperationMetadata", + }, +) + + +class NetworkConfig(proto.Message): + r"""Network configuration for ManagementServer instance. + + Attributes: + network (str): + Optional. The resource name of the Google + Compute Engine VPC network to which the + ManagementServer instance is connected. + peering_mode (google.cloud.backupdr_v1beta.types.NetworkConfig.PeeringMode): + Optional. The network connect mode of the ManagementServer + instance. For this version, only PRIVATE_SERVICE_ACCESS is + supported. + """ + + class PeeringMode(proto.Enum): + r"""VPC peering modes supported by Google Cloud Backup and DR. + + Values: + PEERING_MODE_UNSPECIFIED (0): + Peering mode not set. + PRIVATE_SERVICE_ACCESS (1): + Connect using Private Service Access to the + Management Server. Private services access + provides an IP address range for multiple Google + Cloud services, including Google Cloud Backup + and DR. + """ + + PEERING_MODE_UNSPECIFIED = 0 + PRIVATE_SERVICE_ACCESS = 1 + + network: str = proto.Field( + proto.STRING, + number=1, + ) + peering_mode: PeeringMode = proto.Field( + proto.ENUM, + number=2, + enum=PeeringMode, + ) + + +class ManagementURI(proto.Message): + r"""ManagementURI for the Management Server resource. + + Attributes: + web_ui (str): + Output only. The ManagementServer AGM/RD + WebUI URL. + api (str): + Output only. The ManagementServer AGM/RD API + URL. + """ + + web_ui: str = proto.Field( + proto.STRING, + number=1, + ) + api: str = proto.Field( + proto.STRING, + number=2, + ) + + +class WorkforceIdentityBasedManagementURI(proto.Message): + r"""ManagementURI depending on the Workforce Identity i.e. either + 1p or 3p. + + Attributes: + first_party_management_uri (str): + Output only. First party Management URI for + Google Identities. + third_party_management_uri (str): + Output only. Third party Management URI for + External Identity Providers. + """ + + first_party_management_uri: str = proto.Field( + proto.STRING, + number=1, + ) + third_party_management_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class WorkforceIdentityBasedOAuth2ClientID(proto.Message): + r"""OAuth Client ID depending on the Workforce Identity i.e. + either 1p or 3p, + + Attributes: + first_party_oauth2_client_id (str): + Output only. First party OAuth Client ID for + Google Identities. + third_party_oauth2_client_id (str): + Output only. Third party OAuth Client ID for + External Identity Providers. + """ + + first_party_oauth2_client_id: str = proto.Field( + proto.STRING, + number=1, + ) + third_party_oauth2_client_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ManagementServer(proto.Message): + r"""ManagementServer describes a single BackupDR ManagementServer + instance. + + Attributes: + name (str): + Output only. Identifier. The resource name. + description (str): + Optional. The description of the + ManagementServer instance (2048 characters or + less). + labels (MutableMapping[str, str]): + Optional. Resource labels to represent user provided + metadata. Labels currently defined: + + 1. migrate_from_go= If set to true, the MS is + created in migration ready mode. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + updated. + type_ (google.cloud.backupdr_v1beta.types.ManagementServer.InstanceType): + Optional. The type of the ManagementServer + resource. + management_uri (google.cloud.backupdr_v1beta.types.ManagementURI): + Output only. The hostname or ip address of + the exposed AGM endpoints, used by clients to + connect to AGM/RD graphical user interface and + APIs. + workforce_identity_based_management_uri (google.cloud.backupdr_v1beta.types.WorkforceIdentityBasedManagementURI): + Output only. The hostnames of the exposed AGM + endpoints for both types of user i.e. 1p and 3p, + used to connect AGM/RM UI. + state (google.cloud.backupdr_v1beta.types.ManagementServer.InstanceState): + Output only. The ManagementServer state. + networks (MutableSequence[google.cloud.backupdr_v1beta.types.NetworkConfig]): + Optional. VPC networks to which the + ManagementServer instance is connected. For this + version, only a single network is supported. + This field is optional if MS is created without + PSA + etag (str): + Optional. Server specified ETag for the + ManagementServer resource to prevent + simultaneous updates from overwiting each other. + oauth2_client_id (str): + Output only. The OAuth 2.0 client id is required to make API + calls to the Backup and DR instance API of this + ManagementServer. This is the value that should be provided + in the 'aud' field of the OIDC ID Token (see openid + specification + https://openid.net/specs/openid-connect-core-1_0.html#IDToken). + workforce_identity_based_oauth2_client_id (google.cloud.backupdr_v1beta.types.WorkforceIdentityBasedOAuth2ClientID): + Output only. The OAuth client IDs for both + types of user i.e. 1p and 3p. + ba_proxy_uri (MutableSequence[str]): + Output only. The hostname or ip address of + the exposed AGM endpoints, used by BAs to + connect to BA proxy. + satisfies_pzs (google.protobuf.wrappers_pb2.BoolValue): + Output only. Reserved for future use. + satisfies_pzi (bool): + Output only. Reserved for future use. + """ + + class InstanceType(proto.Enum): + r"""Type of backup service resource. + + Values: + INSTANCE_TYPE_UNSPECIFIED (0): + Instance type is not mentioned. + BACKUP_RESTORE (1): + Instance for backup and restore management + (i.e., AGM). + """ + + INSTANCE_TYPE_UNSPECIFIED = 0 + BACKUP_RESTORE = 1 + + class InstanceState(proto.Enum): + r"""State of Management server instance. + + Values: + INSTANCE_STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The instance is being created. + READY (2): + The instance has been created and is fully + usable. + UPDATING (3): + The instance configuration is being updated. + Certain kinds of updates may cause the instance + to become unusable while the update is in + progress. + DELETING (4): + The instance is being deleted. + REPAIRING (5): + The instance is being repaired and may be + unstable. + MAINTENANCE (6): + Maintenance is being performed on this + instance. + ERROR (7): + The instance is experiencing an issue and + might be unusable. You can get further details + from the statusMessage field of Instance + resource. + """ + + INSTANCE_STATE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + UPDATING = 3 + DELETING = 4 + REPAIRING = 5 + MAINTENANCE = 6 + ERROR = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + type_: InstanceType = proto.Field( + proto.ENUM, + number=14, + enum=InstanceType, + ) + management_uri: "ManagementURI" = proto.Field( + proto.MESSAGE, + number=11, + message="ManagementURI", + ) + workforce_identity_based_management_uri: "WorkforceIdentityBasedManagementURI" = ( + proto.Field( + proto.MESSAGE, + number=16, + message="WorkforceIdentityBasedManagementURI", + ) + ) + state: InstanceState = proto.Field( + proto.ENUM, + number=7, + enum=InstanceState, + ) + networks: MutableSequence["NetworkConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="NetworkConfig", + ) + etag: str = proto.Field( + proto.STRING, + number=13, + ) + oauth2_client_id: str = proto.Field( + proto.STRING, + number=15, + ) + workforce_identity_based_oauth2_client_id: "WorkforceIdentityBasedOAuth2ClientID" = proto.Field( + proto.MESSAGE, + number=17, + message="WorkforceIdentityBasedOAuth2ClientID", + ) + ba_proxy_uri: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=18, + ) + satisfies_pzs: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=19, + message=wrappers_pb2.BoolValue, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=20, + ) + + +class ListManagementServersRequest(proto.Message): + r"""Request message for listing management servers. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The project and location for which to retrieve + management servers information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. To retrieve management servers + for all locations, use "-" for the '{location}' value. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results. + + This field is a member of `oneof`_ ``_filter``. + order_by (str): + Optional. Hint for how to order the results. + + This field is a member of `oneof`_ ``_order_by``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + +class ListManagementServersResponse(proto.Message): + r"""Response message for listing management servers. + + Attributes: + management_servers (MutableSequence[google.cloud.backupdr_v1beta.types.ManagementServer]): + The list of ManagementServer instances in the + project for the specified location. + + If the '{location}' value in the request is "-", + the response contains a list of instances from + all locations. In case any location is + unreachable, the response will only return + management servers in reachable locations and + the 'unreachable' field will be populated with a + list of unreachable locations. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + management_servers: MutableSequence["ManagementServer"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ManagementServer", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetManagementServerRequest(proto.Message): + r"""Request message for getting a management server instance. + + Attributes: + name (str): + Required. Name of the management server resource name, in + the format + 'projects/{project_id}/locations/{location}/managementServers/{resource_name}' + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateManagementServerRequest(proto.Message): + r"""Request message for creating a management server instance. + + Attributes: + parent (str): + Required. The management server project and location in the + format 'projects/{project_id}/locations/{location}'. In + Google Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + management_server_id (str): + Required. The name of the management server + to create. The name must be unique for the + specified project and location. + management_server (google.cloud.backupdr_v1beta.types.ManagementServer): + Required. A [management server + resource][google.cloud.backupdr.v1.ManagementServer] + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + management_server_id: str = proto.Field( + proto.STRING, + number=2, + ) + management_server: "ManagementServer" = proto.Field( + proto.MESSAGE, + number=3, + message="ManagementServer", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteManagementServerRequest(proto.Message): + r"""Request message for deleting a management server instance. + + Attributes: + name (str): + Required. Name of the resource + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class InitializeServiceRequest(proto.Message): + r"""Request message for initializing the service. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_sql_instance_initialization_config (google.cloud.backupdr_v1beta.types.CloudSqlInstanceInitializationConfig): + Optional. The configuration for initializing + a Cloud SQL instance. + + This field is a member of `oneof`_ ``initialization_config``. + name (str): + Required. The resource name of the serviceConfig used to + initialize the service. The location must be the location of + the BackupVault. Format: + ``projects/{project_id}/locations/{location}/serviceConfig``. + resource_type (str): + Required. The resource type to which the + default service config will be applied. Examples + include, "compute.googleapis.com/Instance" and + "storage.googleapis.com/Bucket". + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + backup_plan_location (str): + Optional. The location where the BackupPlan will be created. + This field is required for multi-region BackupVaults and is + optional for regional BackupVaults. It is useful when + creating a Backup Vault in a multi-region, allowing the + BackupPlan to reside in a specific region within that + multi-region. If this field is not provided, the BackupPlan + will be created in the same location as specified in the + ``name`` field. + validate_only (bool): + Optional. If set, validates the request and + returns the result, but does not actually run + it. + """ + + cloud_sql_instance_initialization_config: backupvault_cloudsql.CloudSqlInstanceInitializationConfig = proto.Field( + proto.MESSAGE, + number=4, + oneof="initialization_config", + message=backupvault_cloudsql.CloudSqlInstanceInitializationConfig, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + backup_plan_location: str = proto.Field( + proto.STRING, + number=6, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class InitializeServiceResponse(proto.Message): + r"""Response message for initializing the service. + + Attributes: + backup_vault_name (str): + The resource name of the default ``BackupVault`` created. + Format: + ``projects/{project_id}/locations/{location}/backupVaults/{backup_vault_id}``. + backup_plan_name (str): + The resource name of the default ``BackupPlan`` created. + Format: + ``projects/{project_id}/locations/{location}/backupPlans/{backup_plan_id}``. + """ + + backup_vault_name: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to 'Code.CANCELLED'. + api_version (str): + Output only. API version used to start the + operation. + additional_info (MutableMapping[str, str]): + Output only. AdditionalInfo contains + additional Info related to backup plan + association resource. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + additional_info: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupplan.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupplan.py new file mode 100644 index 000000000000..7a496c571b47 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupplan.py @@ -0,0 +1,1020 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.dayofweek_pb2 as dayofweek_pb2 # type: ignore +import google.type.month_pb2 as month_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "BackupPlan", + "BackupRule", + "StandardSchedule", + "BackupWindow", + "WeekDayOfMonth", + "CreateBackupPlanRequest", + "ListBackupPlansRequest", + "ListBackupPlansResponse", + "GetBackupPlanRequest", + "DeleteBackupPlanRequest", + "UpdateBackupPlanRequest", + "BackupPlanRevision", + "GetBackupPlanRevisionRequest", + "ListBackupPlanRevisionsRequest", + "ListBackupPlanRevisionsResponse", + "DiskBackupPlanProperties", + "ComputeInstanceBackupPlanProperties", + }, +) + + +class BackupPlan(proto.Message): + r"""A ``BackupPlan`` specifies some common fields, such as + ``description`` as well as one or more ``BackupRule`` messages. Each + ``BackupRule`` has a retention policy and defines a schedule by + which the system is to perform backup workloads. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disk_backup_plan_properties (google.cloud.backupdr_v1beta.types.DiskBackupPlanProperties): + Optional. Defines optional properties + specific to backups of disk-based resources, + such as Compute Engine Persistent Disks. This + includes settings like whether to perform a + guest flush. + + This field is a member of `oneof`_ ``resource_properties``. + compute_instance_backup_plan_properties (google.cloud.backupdr_v1beta.types.ComputeInstanceBackupPlanProperties): + Optional. Defines optional properties + specific to backups of compute instance based + resources, such as Compute Engine Instances. + This includes settings like whether to perform a + guest flush. + + This field is a member of `oneof`_ ``resource_properties``. + name (str): + Output only. Identifier. The resource name of the + ``BackupPlan``. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}`` + description (str): + Optional. The description of the ``BackupPlan`` resource. + + The description allows for additional details about + ``BackupPlan`` and its use cases to be provided. An example + description is the following: "This is a backup plan that + performs a daily backup at 6pm and retains data for 3 + months". The description must be at most 2048 characters. + labels (MutableMapping[str, str]): + Optional. This collection of key/value pairs + allows for custom labels to be supplied by the + user. Example, {"tag": "Weekly"}. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the ``BackupPlan`` was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the ``BackupPlan`` was last updated. + backup_rules (MutableSequence[google.cloud.backupdr_v1beta.types.BackupRule]): + Optional. The backup rules for this ``BackupPlan``. + max_custom_on_demand_retention_days (int): + Optional. Optional field to configure the + maximum number of days for which a backup can be + retained. This field is only applicable for + on-demand backups taken with custom retention + value. + state (google.cloud.backupdr_v1beta.types.BackupPlan.State): + Output only. The ``State`` for the ``BackupPlan``. + resource_type (str): + Required. The resource type to which the ``BackupPlan`` will + be applied. Examples include, + "compute.googleapis.com/Instance", + "sqladmin.googleapis.com/Instance", + "alloydb.googleapis.com/Cluster", + "compute.googleapis.com/Disk". + etag (str): + Optional. ``etag`` is returned from the service in the + response. As a user of the service, you may provide an etag + value in this field to prevent stale resources. + backup_vault (str): + Required. Resource name of backup vault which + will be used as storage location for backups. + Format: + + projects/{project}/locations/{location}/backupVaults/{backupvault} + backup_vault_service_account (str): + Output only. The Google Cloud service account + to be used by the BackupVault for taking + backups. Specify the email address of the Backup + Vault Service Account. + log_retention_days (int): + Optional. Applicable only for Cloud SQL resource_type. + + Configures how long logs will be stored. It is defined in + “days”. This value should be greater than or equal to + minimum enforced log retention duration of the backup vault. + supported_resource_types (MutableSequence[str]): + Output only. All resource types to which + backupPlan can be applied. + revision_id (str): + Output only. The user friendly revision ID of the + ``BackupPlanRevision``. + + Example: v0, v1, v2, etc. + revision_name (str): + Output only. The resource id of the ``BackupPlanRevision``. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision_id}`` + """ + + class State(proto.Enum): + r"""``State`` enumerates the possible states for a ``BackupPlan``. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The resource is being created. + ACTIVE (2): + The resource has been created and is fully + usable. + DELETING (3): + The resource is being deleted. + INACTIVE (4): + The resource has been created but is not + usable. + UPDATING (5): + The resource is being updated. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + INACTIVE = 4 + UPDATING = 5 + + disk_backup_plan_properties: "DiskBackupPlanProperties" = proto.Field( + proto.MESSAGE, + number=19, + oneof="resource_properties", + message="DiskBackupPlanProperties", + ) + compute_instance_backup_plan_properties: "ComputeInstanceBackupPlanProperties" = ( + proto.Field( + proto.MESSAGE, + number=20, + oneof="resource_properties", + message="ComputeInstanceBackupPlanProperties", + ) + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + backup_rules: MutableSequence["BackupRule"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="BackupRule", + ) + max_custom_on_demand_retention_days: int = proto.Field( + proto.INT32, + number=18, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + resource_type: str = proto.Field( + proto.STRING, + number=8, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + backup_vault: str = proto.Field( + proto.STRING, + number=10, + ) + backup_vault_service_account: str = proto.Field( + proto.STRING, + number=11, + ) + log_retention_days: int = proto.Field( + proto.INT64, + number=12, + ) + supported_resource_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + revision_id: str = proto.Field( + proto.STRING, + number=14, + ) + revision_name: str = proto.Field( + proto.STRING, + number=15, + ) + + +class BackupRule(proto.Message): + r"""``BackupRule`` binds the backup schedule to a retention policy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + standard_schedule (google.cloud.backupdr_v1beta.types.StandardSchedule): + Optional. Defines a schedule that runs within + the confines of a defined window of time. + + This field is a member of `oneof`_ ``backup_schedule_oneof``. + rule_id (str): + Required. Immutable. The unique id of this ``BackupRule``. + The ``rule_id`` is unique per ``BackupPlan``.The ``rule_id`` + must start with a lowercase letter followed by up to 62 + lowercase letters, numbers, or hyphens. Pattern, + /[a-z][a-z0-9-]{,62}/. + backup_retention_days (int): + Required. Configures the duration for which + backup data will be kept. It is defined in + “days”. The value should be greater than or + equal to minimum enforced retention of the + backup vault. + + Minimum value is 1 and maximum value is 36159 + for custom retention on-demand backup. + Minimum and maximum values are workload specific + for all other rules. Note: Longer retention can + lead to higher storage costs post introductory + trial. We recommend starting with a short + duration of 3 days or less. + """ + + standard_schedule: "StandardSchedule" = proto.Field( + proto.MESSAGE, + number=5, + oneof="backup_schedule_oneof", + message="StandardSchedule", + ) + rule_id: str = proto.Field( + proto.STRING, + number=1, + ) + backup_retention_days: int = proto.Field( + proto.INT32, + number=4, + ) + + +class StandardSchedule(proto.Message): + r"""``StandardSchedule`` defines a schedule that run within the confines + of a defined window of days. We can define recurrence type for + schedule as HOURLY, DAILY, WEEKLY, MONTHLY or YEARLY. + + Attributes: + recurrence_type (google.cloud.backupdr_v1beta.types.StandardSchedule.RecurrenceType): + Required. Specifies the ``RecurrenceType`` for the schedule. + hourly_frequency (int): + Optional. Specifies frequency for hourly backups. A hourly + frequency of 2 means jobs will run every 2 hours from start + time till end time defined. + + This is required for ``recurrence_type``, ``HOURLY`` and is + not applicable otherwise. A validation error will occur if a + value is supplied and ``recurrence_type`` is not ``HOURLY``. + + The supported values for each resource type are as follows: + + - ``compute.googleapis.com/Instance``: 1-23 + - ``compute.googleapis.com/Disk``: 1-23 + - ``sqladmin.googleapis.com/Instance``: 6-23 + - ``alloydb.googleapis.com/Cluster``: 1-23 + - ``file.googleapis.com/Instance``: 1-23 + + Refer to link + https://cloud.google.com/backup-disaster-recovery/docs/concepts/cloud_best_practices + for more details. + days_of_week (MutableSequence[google.type.dayofweek_pb2.DayOfWeek]): + Optional. Specifies days of week like, MONDAY or TUESDAY, on + which jobs will run. + + This is required for ``recurrence_type``, ``WEEKLY`` and is + not applicable otherwise. A validation error will occur if a + value is supplied and ``recurrence_type`` is not ``WEEKLY``. + days_of_month (MutableSequence[int]): + Optional. Specifies days of months like 1, 5, or 14 on which + jobs will run. + + Values for ``days_of_month`` are only applicable for + ``recurrence_type``, ``MONTHLY`` and ``YEARLY``. A + validation error will occur if other values are supplied. + week_day_of_month (google.cloud.backupdr_v1beta.types.WeekDayOfMonth): + Optional. Specifies a week day of the month like, FIRST + SUNDAY or LAST MONDAY, on which jobs will run. This will be + specified by two fields in ``WeekDayOfMonth``, one for the + day, e.g. ``MONDAY``, and one for the week, e.g. ``LAST``. + + This field is only applicable for ``recurrence_type``, + ``MONTHLY`` and ``YEARLY``. A validation error will occur if + other values are supplied. + months (MutableSequence[google.type.month_pb2.Month]): + Optional. Specifies the months of year, like ``FEBRUARY`` + and/or ``MAY``, on which jobs will run. + + This field is only applicable when ``recurrence_type`` is + ``YEARLY``. A validation error will occur if other values + are supplied. + backup_window (google.cloud.backupdr_v1beta.types.BackupWindow): + Required. A BackupWindow defines the window of day during + which backup jobs will run. Jobs are queued at the beginning + of the window and will be marked as ``NOT_RUN`` if they do + not start by the end of the window. + + Note: running jobs will not be cancelled at the end of the + window. + time_zone (str): + Required. The time zone to be used when interpreting the + schedule. The value of this field must be a time zone name + from the IANA tz database. See + https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + for the list of valid timezone names. For e.g., + Europe/Paris. + """ + + class RecurrenceType(proto.Enum): + r"""``RecurrenceTypes`` enumerates the applicable periodicity for the + schedule. + + Values: + RECURRENCE_TYPE_UNSPECIFIED (0): + recurrence type not set + HOURLY (1): + The ``BackupRule`` is to be applied hourly. + DAILY (2): + The ``BackupRule`` is to be applied daily. + WEEKLY (3): + The ``BackupRule`` is to be applied weekly. + MONTHLY (4): + The ``BackupRule`` is to be applied monthly. + YEARLY (5): + The ``BackupRule`` is to be applied yearly. + """ + + RECURRENCE_TYPE_UNSPECIFIED = 0 + HOURLY = 1 + DAILY = 2 + WEEKLY = 3 + MONTHLY = 4 + YEARLY = 5 + + recurrence_type: RecurrenceType = proto.Field( + proto.ENUM, + number=1, + enum=RecurrenceType, + ) + hourly_frequency: int = proto.Field( + proto.INT32, + number=2, + ) + days_of_week: MutableSequence[dayofweek_pb2.DayOfWeek] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=dayofweek_pb2.DayOfWeek, + ) + days_of_month: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=4, + ) + week_day_of_month: "WeekDayOfMonth" = proto.Field( + proto.MESSAGE, + number=5, + message="WeekDayOfMonth", + ) + months: MutableSequence[month_pb2.Month] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=month_pb2.Month, + ) + backup_window: "BackupWindow" = proto.Field( + proto.MESSAGE, + number=7, + message="BackupWindow", + ) + time_zone: str = proto.Field( + proto.STRING, + number=8, + ) + + +class BackupWindow(proto.Message): + r"""``BackupWindow`` defines a window of the day during which backup + jobs will run. + + Attributes: + start_hour_of_day (int): + Required. The hour of day (0-23) when the + window starts for e.g. if value of start hour of + day is 6 that mean backup window start at 6:00. + end_hour_of_day (int): + Required. The hour of day (1-24) when the window end for + e.g. if value of end hour of day is 10 that mean backup + window end time is 10:00. + + End hour of day should be greater than start hour of day. 0 + <= start_hour_of_day < end_hour_of_day <= 24 + + End hour of day is not include in backup window that mean if + end_hour_of_day= 10 jobs should start before 10:00. + """ + + start_hour_of_day: int = proto.Field( + proto.INT32, + number=1, + ) + end_hour_of_day: int = proto.Field( + proto.INT32, + number=2, + ) + + +class WeekDayOfMonth(proto.Message): + r"""``WeekDayOfMonth`` defines the week day of the month on which the + backups will run. The message combines a ``WeekOfMonth`` and + ``DayOfWeek`` to produce values like ``FIRST``/``MONDAY`` or + ``LAST``/``FRIDAY``. + + Attributes: + week_of_month (google.cloud.backupdr_v1beta.types.WeekDayOfMonth.WeekOfMonth): + Required. Specifies the week of the month. + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + Required. Specifies the day of the week. + """ + + class WeekOfMonth(proto.Enum): + r"""``WeekOfMonth`` enumerates possible weeks in the month, e.g. the + first, third, or last week of the month. + + Values: + WEEK_OF_MONTH_UNSPECIFIED (0): + The zero value. Do not use. + FIRST (1): + The first week of the month. + SECOND (2): + The second week of the month. + THIRD (3): + The third week of the month. + FOURTH (4): + The fourth week of the month. + LAST (5): + The last week of the month. + """ + + WEEK_OF_MONTH_UNSPECIFIED = 0 + FIRST = 1 + SECOND = 2 + THIRD = 3 + FOURTH = 4 + LAST = 5 + + week_of_month: WeekOfMonth = proto.Field( + proto.ENUM, + number=1, + enum=WeekOfMonth, + ) + day_of_week: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + +class CreateBackupPlanRequest(proto.Message): + r"""The request message for creating a ``BackupPlan``. + + Attributes: + parent (str): + Required. The ``BackupPlan`` project and location in the + format ``projects/{project}/locations/{location}``. In + Google Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + backup_plan_id (str): + Required. The name of the ``BackupPlan`` to create. The name + must be unique for the specified project and location.The + name must start with a lowercase letter followed by up to 62 + lowercase letters, numbers, or hyphens. Pattern, + /[a-z][a-z0-9-]{,62}/. + backup_plan (google.cloud.backupdr_v1beta.types.BackupPlan): + Required. The ``BackupPlan`` resource object to create. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup_plan: "BackupPlan" = proto.Field( + proto.MESSAGE, + number=3, + message="BackupPlan", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListBackupPlansRequest(proto.Message): + r"""The request message for getting a list ``BackupPlan``. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + ``BackupPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google Cloud + Backup and DR, locations map to Google Cloud regions, for + e.g. **us-central1**. To retrieve backup plans for all + locations, use "-" for the ``{location}`` value. + page_size (int): + Optional. The maximum number of ``BackupPlans`` to return in + a single response. If not specified, a default value will be + chosen by the service. Note that the response may include a + partial list and a caller should only rely on the response's + [next_page_token][google.cloud.backupdr.v1beta.ListBackupPlansResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + Optional. The value of + [next_page_token][google.cloud.backupdr.v1beta.ListBackupPlansResponse.next_page_token] + received from a previous ``ListBackupPlans`` call. Provide + this to retrieve the subsequent page in a multi-page list of + results. When paginating, all other parameters provided to + ``ListBackupPlans`` must match the call that provided the + page token. + filter (str): + Optional. Field match expression used to + filter the results. + order_by (str): + Optional. Field by which to sort the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListBackupPlansResponse(proto.Message): + r"""The response message for getting a list of ``BackupPlan``. + + Attributes: + backup_plans (MutableSequence[google.cloud.backupdr_v1beta.types.BackupPlan]): + The list of ``BackupPlans`` in the project for the specified + location. + + If the ``{location}`` value in the request is "-", the + response contains a list of resources from all locations. In + case any location is unreachable, the response will only + return backup plans in reachable locations and the + 'unreachable' field will be populated with a list of + unreachable locations. BackupPlan + next_page_token (str): + A token which may be sent as + [page_token][google.cloud.backupdr.v1beta.ListBackupPlansRequest.page_token] + in a subsequent ``ListBackupPlans`` call to retrieve the + next page of results. If this field is omitted or empty, + then there are no more results to return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backup_plans: MutableSequence["BackupPlan"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupPlan", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetBackupPlanRequest(proto.Message): + r"""The request message for getting a ``BackupPlan``. + + Attributes: + name (str): + Required. The resource name of the ``BackupPlan`` to + retrieve. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteBackupPlanRequest(proto.Message): + r"""The request message for deleting a ``BackupPlan``. + + Attributes: + name (str): + Required. The resource name of the ``BackupPlan`` to delete. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}`` + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateBackupPlanRequest(proto.Message): + r"""Request message for updating a backup plan. + + Attributes: + backup_plan (google.cloud.backupdr_v1beta.types.BackupPlan): + Required. The resource being updated + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field mask is used + to specify the fields to be overwritten in the BackupPlan + resource by the update. The fields specified in the + update_mask are relative to the resource, not the full + request. A field will be overwritten if it is in the mask. + If the user does not provide a mask then the request will + fail. Currently, these fields are supported in update: + description, schedules, retention period, adding and + removing Backup Rules. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + backup_plan: "BackupPlan" = proto.Field( + proto.MESSAGE, + number=1, + message="BackupPlan", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BackupPlanRevision(proto.Message): + r"""``BackupPlanRevision`` represents a snapshot of a ``BackupPlan`` at + a point in time. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + ``BackupPlanRevision``. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision}`` + revision_id (str): + Output only. The user friendly revision ID of the + ``BackupPlanRevision``. + + Example: v0, v1, v2, etc. + state (google.cloud.backupdr_v1beta.types.BackupPlanRevision.State): + Output only. Resource State + backup_plan_snapshot (google.cloud.backupdr_v1beta.types.BackupPlan): + The Backup Plan being encompassed by this + revision. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp that the revision + was created. + """ + + class State(proto.Enum): + r"""The state of the ``BackupPlanRevision``. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The resource is being created. + ACTIVE (2): + The resource has been created and is fully + usable. + DELETING (3): + The resource is being deleted. + INACTIVE (4): + The resource has been created but is not + usable. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + INACTIVE = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + backup_plan_snapshot: "BackupPlan" = proto.Field( + proto.MESSAGE, + number=4, + message="BackupPlan", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class GetBackupPlanRevisionRequest(proto.Message): + r"""The request message for getting a ``BackupPlanRevision``. + + Attributes: + name (str): + Required. The resource name of the ``BackupPlanRevision`` to + retrieve. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBackupPlanRevisionsRequest(proto.Message): + r"""The request message for getting a list of ``BackupPlanRevision``. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + ``BackupPlanRevisions`` information. Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}``. + In Google Cloud Backup and DR, locations map to Google Cloud + regions, for e.g. **us-central1**. + page_size (int): + Optional. The maximum number of ``BackupPlans`` to return in + a single response. If not specified, a default value will be + chosen by the service. Note that the response may include a + partial list and a caller should only rely on the response's + [next_page_token][google.cloud.backupdr.v1beta.ListBackupPlansResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + Optional. The value of + [next_page_token][google.cloud.backupdr.v1beta.ListBackupPlansResponse.next_page_token] + received from a previous ``ListBackupPlans`` call. Provide + this to retrieve the subsequent page in a multi-page list of + results. When paginating, all other parameters provided to + ``ListBackupPlans`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBackupPlanRevisionsResponse(proto.Message): + r"""The response message for getting a list of ``BackupPlanRevision``. + + Attributes: + backup_plan_revisions (MutableSequence[google.cloud.backupdr_v1beta.types.BackupPlanRevision]): + The list of ``BackupPlanRevisions`` in the project for the + specified location. + + If the ``{location}`` value in the request is "-", the + response contains a list of resources from all locations. In + case any location is unreachable, the response will only + return backup plans in reachable locations and the + 'unreachable' field will be populated with a list of + unreachable locations. + next_page_token (str): + A token which may be sent as + [page_token][google.cloud.backupdr.v1beta.ListBackupPlanRevisionsRequest.page_token] + in a subsequent ``ListBackupPlanRevisions`` call to retrieve + the next page of results. If this field is omitted or empty, + then there are no more results to return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backup_plan_revisions: MutableSequence["BackupPlanRevision"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupPlanRevision", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DiskBackupPlanProperties(proto.Message): + r"""Properties for a disk backup plan. + + Attributes: + guest_flush (bool): + Optional. Indicates whether to perform a + guest flush operation before taking a disk + backup. When set to false, the system will + create crash-consistent backups. Default value + is false. + """ + + guest_flush: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class ComputeInstanceBackupPlanProperties(proto.Message): + r"""Properties for a compute instance backup plan. + + Attributes: + guest_flush (bool): + Optional. Indicates whether to perform a + guest flush operation before taking a compute + backup. When set to false, the system will + create crash-consistent backups. Default value + is false. + """ + + guest_flush: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupplanassociation.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupplanassociation.py new file mode 100644 index 000000000000..92da10463a1f --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupplanassociation.py @@ -0,0 +1,711 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1beta.types import backupvault_alloydb, backupvault_cloudsql + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "BackupPlanAssociation", + "RuleConfigInfo", + "CreateBackupPlanAssociationRequest", + "ListBackupPlanAssociationsRequest", + "ListBackupPlanAssociationsResponse", + "FetchBackupPlanAssociationsForResourceTypeRequest", + "FetchBackupPlanAssociationsForResourceTypeResponse", + "GetBackupPlanAssociationRequest", + "DeleteBackupPlanAssociationRequest", + "UpdateBackupPlanAssociationRequest", + "TriggerBackupRequest", + }, +) + + +class BackupPlanAssociation(proto.Message): + r"""A BackupPlanAssociation represents a single + BackupPlanAssociation which contains details like workload, + backup plan etc + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_sql_instance_backup_plan_association_properties (google.cloud.backupdr_v1beta.types.CloudSqlInstanceBackupPlanAssociationProperties): + Output only. Cloud SQL instance's backup plan + association properties. + + This field is a member of `oneof`_ ``resource_properties``. + alloydb_cluster_backup_plan_association_properties (google.cloud.backupdr_v1beta.types.AlloyDBClusterBackupPlanAssociationProperties): + Output only. AlloyDB cluster's backup plan + association properties. + + This field is a member of `oneof`_ ``resource_properties``. + name (str): + Output only. Identifier. The resource name of + BackupPlanAssociation in below format Format : + + projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId} + resource_type (str): + Required. Immutable. Resource type of + workload on which backupplan is applied + resource (str): + Required. Immutable. Resource name of + workload on which the backup plan is applied. + + The format can either be the resource name + (e.g., + "projects/my-project/zones/us-central1-a/instances/my-instance") + or the full resource URI (e.g., + "https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/instances/my-instance"). + backup_plan (str): + Required. Resource name of backup plan which + needs to be applied on workload. Format: + + projects/{project}/locations/{location}/backupPlans/{backupPlanId} + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + updated. + state (google.cloud.backupdr_v1beta.types.BackupPlanAssociation.State): + Output only. The BackupPlanAssociation + resource state. + rules_config_info (MutableSequence[google.cloud.backupdr_v1beta.types.RuleConfigInfo]): + Output only. The config info related to + backup rules. + data_source (str): + Output only. Resource name of data source + which will be used as storage location for + backups taken. Format : + + projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource} + backup_plan_revision_id (str): + Output only. The user friendly revision ID of the + ``BackupPlanRevision``. + + Example: v0, v1, v2, etc. + backup_plan_revision_name (str): + Output only. The resource id of the ``BackupPlanRevision``. + + Format: + ``projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision_id}`` + auto_protection_policy_binding (str): + Output only. The resource name of the + ``AutoProtectionPolicyBinding`` that manages this + association, if any. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{policy}/bindings/{binding}``. + """ + + class State(proto.Enum): + r"""Enum for State of BackupPlan Association + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The resource is being created. + ACTIVE (2): + The resource has been created and is fully + usable. + DELETING (3): + The resource is being deleted. + INACTIVE (4): + The resource has been created but is not + usable. + UPDATING (5): + The resource is being updated. + PAUSED (6): + The resource has been created but backups are + paused. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + INACTIVE = 4 + UPDATING = 5 + PAUSED = 6 + + cloud_sql_instance_backup_plan_association_properties: backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties = proto.Field( + proto.MESSAGE, + number=10, + oneof="resource_properties", + message=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties, + ) + alloydb_cluster_backup_plan_association_properties: backupvault_alloydb.AlloyDBClusterBackupPlanAssociationProperties = proto.Field( + proto.MESSAGE, + number=15, + oneof="resource_properties", + message=backupvault_alloydb.AlloyDBClusterBackupPlanAssociationProperties, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource: str = proto.Field( + proto.STRING, + number=3, + ) + backup_plan: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + rules_config_info: MutableSequence["RuleConfigInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="RuleConfigInfo", + ) + data_source: str = proto.Field( + proto.STRING, + number=9, + ) + backup_plan_revision_id: str = proto.Field( + proto.STRING, + number=11, + ) + backup_plan_revision_name: str = proto.Field( + proto.STRING, + number=12, + ) + auto_protection_policy_binding: str = proto.Field( + proto.STRING, + number=16, + ) + + +class RuleConfigInfo(proto.Message): + r"""Message for rules config info. + + Attributes: + rule_id (str): + Output only. Backup Rule id fetched from + backup plan. + last_backup_state (google.cloud.backupdr_v1beta.types.RuleConfigInfo.LastBackupState): + Output only. The last backup state for rule. + last_backup_error (google.rpc.status_pb2.Status): + Output only. google.rpc.Status object to + store the last backup error. + last_successful_backup_consistency_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The point in time when the last + successful backup was captured from the source. + """ + + class LastBackupState(proto.Enum): + r"""Enum for LastBackupState + + Values: + LAST_BACKUP_STATE_UNSPECIFIED (0): + State not set. + FIRST_BACKUP_PENDING (1): + The first backup is pending. + PERMISSION_DENIED (2): + The most recent backup could not be + run/failed because of the lack of permissions. + SUCCEEDED (3): + The last backup operation succeeded. + FAILED (4): + The last backup operation failed. + """ + + LAST_BACKUP_STATE_UNSPECIFIED = 0 + FIRST_BACKUP_PENDING = 1 + PERMISSION_DENIED = 2 + SUCCEEDED = 3 + FAILED = 4 + + rule_id: str = proto.Field( + proto.STRING, + number=1, + ) + last_backup_state: LastBackupState = proto.Field( + proto.ENUM, + number=3, + enum=LastBackupState, + ) + last_backup_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + last_successful_backup_consistency_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class CreateBackupPlanAssociationRequest(proto.Message): + r"""Request message for creating a backup plan. + + Attributes: + parent (str): + Required. The backup plan association project and location + in the format + ``projects/{project_id}/locations/{location}``. In Backup + and DR locations map to Google Cloud regions, for example + **us-central1**. + backup_plan_association_id (str): + Required. The name of the backup plan + association to create. The name must be unique + for the specified project and location. + backup_plan_association (google.cloud.backupdr_v1beta.types.BackupPlanAssociation): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan_association_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup_plan_association: "BackupPlanAssociation" = proto.Field( + proto.MESSAGE, + number=3, + message="BackupPlanAssociation", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListBackupPlanAssociationsRequest(proto.Message): + r"""Request message for List BackupPlanAssociation + + Attributes: + parent (str): + Required. The project and location for which to retrieve + backup Plan Associations information, in the format + ``projects/{project_id}/locations/{location}``. In Backup + and DR, locations map to Google Cloud regions, for example + **us-central1**. To retrieve backup plan associations for + all locations, use "-" for the ``{location}`` value. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListBackupPlanAssociationsResponse(proto.Message): + r"""Response message for List BackupPlanAssociation + + Attributes: + backup_plan_associations (MutableSequence[google.cloud.backupdr_v1beta.types.BackupPlanAssociation]): + The list of Backup Plan Associations in the project for the + specified location. + + If the ``{location}`` value in the request is "-", the + response contains a list of instances from all locations. In + case any location is unreachable, the response will only + return backup plan associations in reachable locations and + the 'unreachable' field will be populated with a list of + unreachable locations. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backup_plan_associations: MutableSequence["BackupPlanAssociation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupPlanAssociation", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class FetchBackupPlanAssociationsForResourceTypeRequest(proto.Message): + r"""Request for the FetchBackupPlanAssociationsForResourceType + method. + + Attributes: + parent (str): + Required. The parent resource name. + Format: projects/{project}/locations/{location} + resource_type (str): + Required. The type of the Google Cloud + resource. Ex: sql.googleapis.com/Instance + page_size (int): + Optional. The maximum number of + BackupPlanAssociations to return. The service + may return fewer than this value. If + unspecified, at most 50 BackupPlanAssociations + will be returned. The maximum value is 100; + values above 100 will be coerced to 100. + page_token (str): + Optional. A page token, received from a previous call of + ``FetchBackupPlanAssociationsForResourceType``. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``FetchBackupPlanAssociationsForResourceType`` must match + the call that provided the page token. + filter (str): + Optional. A filter expression that filters the results + fetched in the response. The expression must specify the + field name, a comparison operator, and the value that you + want to use for filtering. Supported fields: + + - resource + - backup_plan + - state + - data_source + - cloud_sql_instance_backup_plan_association_properties.instance_create_time + order_by (str): + Optional. A comma-separated list of fields to order by, + sorted in ascending order. Use "desc" after a field name for + descending. + + Supported fields: + + - name + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + + +class FetchBackupPlanAssociationsForResourceTypeResponse(proto.Message): + r"""Response for the FetchBackupPlanAssociationsForResourceType + method. + + Attributes: + backup_plan_associations (MutableSequence[google.cloud.backupdr_v1beta.types.BackupPlanAssociation]): + Output only. The BackupPlanAssociations from + the specified parent. + next_page_token (str): + Output only. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + backup_plan_associations: MutableSequence["BackupPlanAssociation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupPlanAssociation", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetBackupPlanAssociationRequest(proto.Message): + r"""Request message for getting a BackupPlanAssociation resource. + + Attributes: + name (str): + Required. Name of the backup plan association resource, in + the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteBackupPlanAssociationRequest(proto.Message): + r"""Request message for deleting a backup plan association. + + Attributes: + name (str): + Required. Name of the backup plan association resource, in + the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + auto_protection_policy_binding (str): + Optional. This field is exclusively used by Backup and DR's + auto-protection feature. The resource name of the + ``AutoProtectionPolicyBinding`` that triggered the deletion + of this association. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{policy}/bindings/{binding}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + auto_protection_policy_binding: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateBackupPlanAssociationRequest(proto.Message): + r"""Request message for updating a backup plan association. + + Attributes: + backup_plan_association (google.cloud.backupdr_v1beta.types.BackupPlanAssociation): + Required. The resource being updated + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field mask is used + to specify the fields to be overwritten in the + BackupPlanAssociation resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then the + request will fail. Currently + backup_plan_association.backup_plan is the only supported + field. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + backup_plan_association: "BackupPlanAssociation" = proto.Field( + proto.MESSAGE, + number=1, + message="BackupPlanAssociation", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class TriggerBackupRequest(proto.Message): + r"""Request message for triggering a backup. + + Attributes: + name (str): + Required. Name of the backup plan association resource, in + the format + ``projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId}`` + rule_id (str): + Optional. backup rule_id for which a backup needs to be + triggered. If not specified, on-demand backup with custom + retention will be triggered. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + custom_retention_days (int): + Optional. The duration for which backup data will be kept, + while taking an on-demand backup with custom retention. It + is defined in "days". It is mutually exclusive with rule_id. + This field is required if rule_id is not provided. + labels (MutableMapping[str, str]): + Optional. Labels to be applied on the backup. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + rule_id: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + custom_retention_days: int = proto.Field( + proto.INT32, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault.py new file mode 100644 index 000000000000..06f7db5ab771 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault.py @@ -0,0 +1,2579 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1beta.types import ( + backupvault_alloydb, + backupvault_ba, + backupvault_cloudsql, + backupvault_disk, + backupvault_gce, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "BackupConfigState", + "BackupView", + "BackupVaultView", + "BackupVault", + "DataSource", + "BackupConfigInfo", + "GcpBackupConfig", + "BackupApplianceBackupConfig", + "DataSourceGcpResource", + "DataSourceBackupApplianceApplication", + "ServiceLockInfo", + "BackupApplianceLockInfo", + "BackupLock", + "Backup", + "CreateBackupVaultRequest", + "ListBackupVaultsRequest", + "ListBackupVaultsResponse", + "FetchUsableBackupVaultsRequest", + "FetchUsableBackupVaultsResponse", + "FetchBackupsForResourceTypeRequest", + "FetchBackupsForResourceTypeResponse", + "GetBackupVaultRequest", + "UpdateBackupVaultRequest", + "DeleteBackupVaultRequest", + "ListDataSourcesRequest", + "ListDataSourcesResponse", + "GetDataSourceRequest", + "UpdateDataSourceRequest", + "ListBackupsRequest", + "ListBackupsResponse", + "GetBackupRequest", + "UpdateBackupRequest", + "DeleteBackupRequest", + "RestoreBackupRequest", + "RestoreBackupResponse", + "TargetResource", + "GcpResource", + "BackupGcpResource", + }, +) + + +class BackupConfigState(proto.Enum): + r"""Backup configuration state. Is the resource configured for + backup? + + Values: + BACKUP_CONFIG_STATE_UNSPECIFIED (0): + The possible states of backup configuration. + Status not set. + ACTIVE (1): + The data source is actively protected (i.e. + there is a BackupPlanAssociation or Appliance + SLA pointing to it) + PASSIVE (2): + The data source is no longer protected (but + may have backups under it) + """ + + BACKUP_CONFIG_STATE_UNSPECIFIED = 0 + ACTIVE = 1 + PASSIVE = 2 + + +class BackupView(proto.Enum): + r"""BackupView contains enum options for Partial and Full view. + + Values: + BACKUP_VIEW_UNSPECIFIED (0): + If the value is not set, the default 'FULL' + view is used. + BACKUP_VIEW_BASIC (1): + Includes basic data about the Backup, but not + the full contents. + BACKUP_VIEW_FULL (2): + Includes all data about the Backup. + This is the default value (for both ListBackups + and GetBackup). + """ + + BACKUP_VIEW_UNSPECIFIED = 0 + BACKUP_VIEW_BASIC = 1 + BACKUP_VIEW_FULL = 2 + + +class BackupVaultView(proto.Enum): + r"""BackupVaultView contains enum options for Partial and Full + view. + + Values: + BACKUP_VAULT_VIEW_UNSPECIFIED (0): + If the value is not set, the default 'FULL' + view is used. + BACKUP_VAULT_VIEW_BASIC (1): + Includes basic data about the Backup Vault, + but not the full contents. + BACKUP_VAULT_VIEW_FULL (2): + Includes all data about the Backup Vault. + This is the default value (for both + ListBackupVaults and GetBackupVault). + """ + + BACKUP_VAULT_VIEW_UNSPECIFIED = 0 + BACKUP_VAULT_VIEW_BASIC = 1 + BACKUP_VAULT_VIEW_FULL = 2 + + +class BackupVault(proto.Message): + r"""Message describing a BackupVault object. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. Name of the backup vault to create. + It must have the + format\ ``"projects/{project}/locations/{location}/backupVaults/{backupvault}"``. + ``{backupvault}`` cannot be changed after creation. It must + be between 3-63 characters long and must be unique within + the project and location. + description (str): + Optional. The description of the BackupVault + instance (2048 characters or less). + + This field is a member of `oneof`_ ``_description``. + labels (MutableMapping[str, str]): + Optional. Resource labels to represent user + provided metadata. No labels currently defined: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + created. + + This field is a member of `oneof`_ ``_create_time``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + updated. + + This field is a member of `oneof`_ ``_update_time``. + backup_minimum_enforced_retention_duration (google.protobuf.duration_pb2.Duration): + Required. The default and minimum enforced + retention for each backup within the backup + vault. The enforced retention for each backup + can be extended. Note: Longer minimum enforced + retention period impacts potential storage costs + post introductory trial. We recommend starting + with a short duration of 3 days or less. + + This field is a member of `oneof`_ ``_backup_minimum_enforced_retention_duration``. + backup_retention_inheritance (google.cloud.backupdr_v1beta.types.BackupVault.BackupRetentionInheritance): + Optional. Setting for how a backup's enforced + retention end time is inherited. + + This field is a member of `oneof`_ ``_backup_retention_inheritance``. + deletable (bool): + Output only. Set to true when there are no + backups nested under this resource. + + This field is a member of `oneof`_ ``_deletable``. + etag (str): + Optional. Server specified ETag for the + backup vault resource to prevent simultaneous + updates from overwiting each other. + + This field is a member of `oneof`_ ``_etag``. + state (google.cloud.backupdr_v1beta.types.BackupVault.State): + Output only. The BackupVault resource + instance state. + effective_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Time after which the BackupVault + resource is locked. + + This field is a member of `oneof`_ ``_effective_time``. + backup_count (int): + Output only. The number of backups in this + backup vault. + service_account (str): + Output only. Service account used by the + BackupVault Service for this BackupVault. The + user should grant this account permissions in + their workload project to enable the service to + run backups and restores there. + total_stored_bytes (int): + Output only. Total size of the storage used + by all backup resources. + uid (str): + Output only. Immutable after resource + creation until resource deletion. + annotations (MutableMapping[str, str]): + Optional. User annotations. See + https://google.aip.dev/128#annotations Stores + small amounts of arbitrary data. + access_restriction (google.cloud.backupdr_v1beta.types.BackupVault.AccessRestriction): + Optional. Restricts access to certain sources and + destinations for data being sent into, or restored from, the + backup vault. Defaults to WITHIN_ORGANIZATION if not + provided during creation. + encryption_config (google.cloud.backupdr_v1beta.types.BackupVault.EncryptionConfig): + Optional. The encryption config of the backup + vault. + + This field is a member of `oneof`_ ``_encryption_config``. + """ + + class BackupRetentionInheritance(proto.Enum): + r"""How a backup's enforced retention end time is inherited. + + Values: + BACKUP_RETENTION_INHERITANCE_UNSPECIFIED (0): + Inheritance behavior not set. This will default to + ``INHERIT_VAULT_RETENTION``. + INHERIT_VAULT_RETENTION (1): + The enforced retention end time of a backup will be + inherited from the backup vault's + ``backup_minimum_enforced_retention_duration`` field. + + This is the default behavior. + MATCH_BACKUP_EXPIRE_TIME (2): + The enforced retention end time of a backup + will always match the expire time of the backup. + + If this is set, the backup's enforced retention + end time will be set to match the expire time + during creation of the backup. When updating, + the ERET and expire time must be updated + together and have the same value. Invalid update + requests will be rejected by the server. + """ + + BACKUP_RETENTION_INHERITANCE_UNSPECIFIED = 0 + INHERIT_VAULT_RETENTION = 1 + MATCH_BACKUP_EXPIRE_TIME = 2 + + class State(proto.Enum): + r"""Holds the state of the backup vault resource. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The backup vault is being created. + ACTIVE (2): + The backup vault has been created and is + fully usable. + DELETING (3): + The backup vault is being deleted. + ERROR (4): + The backup vault is experiencing an issue and + might be unusable. + UPDATING (5): + The backup vault is being updated. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + ERROR = 4 + UPDATING = 5 + + class AccessRestriction(proto.Enum): + r"""Holds the access restriction for the backup vault. + + Values: + ACCESS_RESTRICTION_UNSPECIFIED (0): + Access restriction not set. If user does not provide any + value or pass this value, it will be changed to + WITHIN_ORGANIZATION. + WITHIN_PROJECT (1): + Access to or from resources outside your + current project will be denied. + WITHIN_ORGANIZATION (2): + Access to or from resources outside your + current organization will be denied. + UNRESTRICTED (3): + No access restriction. + WITHIN_ORG_BUT_UNRESTRICTED_FOR_BA (4): + Access to or from resources outside your + current organization will be denied except for + backup appliance. + """ + + ACCESS_RESTRICTION_UNSPECIFIED = 0 + WITHIN_PROJECT = 1 + WITHIN_ORGANIZATION = 2 + UNRESTRICTED = 3 + WITHIN_ORG_BUT_UNRESTRICTED_FOR_BA = 4 + + class EncryptionConfig(proto.Message): + r"""Message describing the EncryptionConfig of backup vault. + This determines how data within the vault is encrypted at rest. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + kms_key_name (str): + Optional. The Cloud KMS key name to encrypt + backups in this backup vault. Must be in the + same region as the vault. Some workload backups + like compute disk backups may use their + inherited source key instead. Format: + + projects/{project}/locations/{location}/keyRings/{ring}/cryptoKeys/{key} + + This field is a member of `oneof`_ ``_kms_key_name``. + """ + + kms_key_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message=timestamp_pb2.Timestamp, + ) + backup_minimum_enforced_retention_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=20, + optional=True, + message=duration_pb2.Duration, + ) + backup_retention_inheritance: BackupRetentionInheritance = proto.Field( + proto.ENUM, + number=27, + optional=True, + enum=BackupRetentionInheritance, + ) + deletable: bool = proto.Field( + proto.BOOL, + number=8, + optional=True, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + effective_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + optional=True, + message=timestamp_pb2.Timestamp, + ) + backup_count: int = proto.Field( + proto.INT64, + number=17, + ) + service_account: str = proto.Field( + proto.STRING, + number=18, + ) + total_stored_bytes: int = proto.Field( + proto.INT64, + number=19, + ) + uid: str = proto.Field( + proto.STRING, + number=21, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=22, + ) + access_restriction: AccessRestriction = proto.Field( + proto.ENUM, + number=24, + enum=AccessRestriction, + ) + encryption_config: EncryptionConfig = proto.Field( + proto.MESSAGE, + number=29, + optional=True, + message=EncryptionConfig, + ) + + +class DataSource(proto.Message): + r"""Message describing a DataSource object. + Datasource object used to represent Datasource details for both + admin and basic view. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + data_source_gcp_resource (google.cloud.backupdr_v1beta.types.DataSourceGcpResource): + The backed up resource is a Google Cloud + resource. The word 'DataSource' was included in + the names to indicate that this is the + representation of the Google Cloud resource used + within the DataSource object. + + This field is a member of `oneof`_ ``source_resource``. + data_source_backup_appliance_application (google.cloud.backupdr_v1beta.types.DataSourceBackupApplianceApplication): + The backed up resource is a backup appliance + application. + + This field is a member of `oneof`_ ``source_resource``. + name (str): + Output only. Identifier. Name of the datasource to create. + It must have the + format\ ``"projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource}"``. + ``{datasource}`` cannot be changed after creation. It must + be between 3-63 characters long and must be unique within + the backup vault. + state (google.cloud.backupdr_v1beta.types.DataSource.State): + Output only. The DataSource resource instance + state. + labels (MutableMapping[str, str]): + Optional. Resource labels to represent user + provided metadata. No labels currently defined: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + created. + + This field is a member of `oneof`_ ``_create_time``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + updated. + + This field is a member of `oneof`_ ``_update_time``. + backup_count (int): + Number of backups in the data source. + + This field is a member of `oneof`_ ``_backup_count``. + etag (str): + Server specified ETag for the + ManagementServer resource to prevent + simultaneous updates from overwiting each other. + + This field is a member of `oneof`_ ``_etag``. + total_stored_bytes (int): + The number of bytes (metadata and data) + stored in this datasource. + + This field is a member of `oneof`_ ``_total_stored_bytes``. + config_state (google.cloud.backupdr_v1beta.types.BackupConfigState): + Output only. The backup configuration state. + backup_config_info (google.cloud.backupdr_v1beta.types.BackupConfigInfo): + Output only. Details of how the resource is + configured for backup. + backup_blocked_by_vault_access_restriction (bool): + Output only. This field is set to true if the + backup is blocked by vault access restriction. + """ + + class State(proto.Enum): + r"""Holds the state of the data source resource. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The data source is being created. + ACTIVE (2): + The data source has been created and is fully + usable. + DELETING (3): + The data source is being deleted. + ERROR (4): + The data source is experiencing an issue and + might be unusable. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + ERROR = 4 + + data_source_gcp_resource: "DataSourceGcpResource" = proto.Field( + proto.MESSAGE, + number=26, + oneof="source_resource", + message="DataSourceGcpResource", + ) + data_source_backup_appliance_application: "DataSourceBackupApplianceApplication" = ( + proto.Field( + proto.MESSAGE, + number=27, + oneof="source_resource", + message="DataSourceBackupApplianceApplication", + ) + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=21, + enum=State, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=timestamp_pb2.Timestamp, + ) + backup_count: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + etag: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + total_stored_bytes: int = proto.Field( + proto.INT64, + number=23, + optional=True, + ) + config_state: "BackupConfigState" = proto.Field( + proto.ENUM, + number=24, + enum="BackupConfigState", + ) + backup_config_info: "BackupConfigInfo" = proto.Field( + proto.MESSAGE, + number=25, + message="BackupConfigInfo", + ) + backup_blocked_by_vault_access_restriction: bool = proto.Field( + proto.BOOL, + number=28, + ) + + +class BackupConfigInfo(proto.Message): + r"""BackupConfigInfo has information about how the resource is + configured for Backup and about the most recent backup to this + vault. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcp_backup_config (google.cloud.backupdr_v1beta.types.GcpBackupConfig): + Configuration for a Google Cloud resource. + + This field is a member of `oneof`_ ``backup_config``. + backup_appliance_backup_config (google.cloud.backupdr_v1beta.types.BackupApplianceBackupConfig): + Configuration for an application backed up by + a Backup Appliance. + + This field is a member of `oneof`_ ``backup_config``. + last_backup_state (google.cloud.backupdr_v1beta.types.BackupConfigInfo.LastBackupState): + Output only. The status of the last backup to + this BackupVault + last_successful_backup_consistency_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. If the last backup were + successful, this field has the consistency date. + last_backup_error (google.rpc.status_pb2.Status): + Output only. If the last backup failed, this + field has the error message. + """ + + class LastBackupState(proto.Enum): + r"""LastBackupstate tracks whether the last backup was not yet + started, successful, failed, or could not be run because of the + lack of permissions. + + Values: + LAST_BACKUP_STATE_UNSPECIFIED (0): + Status not set. + FIRST_BACKUP_PENDING (1): + The first backup has not yet completed + SUCCEEDED (2): + The most recent backup was successful + FAILED (3): + The most recent backup failed + PERMISSION_DENIED (4): + The most recent backup could not be + run/failed because of the lack of permissions + """ + + LAST_BACKUP_STATE_UNSPECIFIED = 0 + FIRST_BACKUP_PENDING = 1 + SUCCEEDED = 2 + FAILED = 3 + PERMISSION_DENIED = 4 + + gcp_backup_config: "GcpBackupConfig" = proto.Field( + proto.MESSAGE, + number=4, + oneof="backup_config", + message="GcpBackupConfig", + ) + backup_appliance_backup_config: "BackupApplianceBackupConfig" = proto.Field( + proto.MESSAGE, + number=5, + oneof="backup_config", + message="BackupApplianceBackupConfig", + ) + last_backup_state: LastBackupState = proto.Field( + proto.ENUM, + number=1, + enum=LastBackupState, + ) + last_successful_backup_consistency_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + last_backup_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + + +class GcpBackupConfig(proto.Message): + r"""GcpBackupConfig captures the Backup configuration details for + Google Cloud resources. All Google Cloud resources regardless of + type are protected with backup plan associations. + + Attributes: + backup_plan (str): + The name of the backup plan. + backup_plan_description (str): + The description of the backup plan. + backup_plan_association (str): + The name of the backup plan association. + backup_plan_rules (MutableSequence[str]): + The names of the backup plan rules which + point to this backupvault + backup_plan_revision_name (str): + The name of the backup plan revision. + backup_plan_revision_id (str): + The user friendly id of the backup plan + revision. E.g. v0, v1 etc. + auto_protection_policy_binding (str): + Output only. The resource name of the + ``AutoProtectionPolicyBinding`` that manages this + datasource, if any. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{policy}/bindings/{binding}``. + """ + + backup_plan: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan_description: str = proto.Field( + proto.STRING, + number=2, + ) + backup_plan_association: str = proto.Field( + proto.STRING, + number=3, + ) + backup_plan_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + backup_plan_revision_name: str = proto.Field( + proto.STRING, + number=5, + ) + backup_plan_revision_id: str = proto.Field( + proto.STRING, + number=6, + ) + auto_protection_policy_binding: str = proto.Field( + proto.STRING, + number=7, + ) + + +class BackupApplianceBackupConfig(proto.Message): + r"""BackupApplianceBackupConfig captures the backup configuration + for applications that are protected by Backup Appliances. + + Attributes: + backup_appliance_name (str): + The name of the backup appliance. + backup_appliance_id (int): + The ID of the backup appliance. + sla_id (int): + The ID of the SLA of this application. + application_name (str): + The name of the application. + host_name (str): + The name of the host where the application is + running. + slt_name (str): + The name of the SLT associated with the + application. + slp_name (str): + The name of the SLP associated with the + application. + """ + + backup_appliance_name: str = proto.Field( + proto.STRING, + number=1, + ) + backup_appliance_id: int = proto.Field( + proto.INT64, + number=2, + ) + sla_id: int = proto.Field( + proto.INT64, + number=3, + ) + application_name: str = proto.Field( + proto.STRING, + number=4, + ) + host_name: str = proto.Field( + proto.STRING, + number=5, + ) + slt_name: str = proto.Field( + proto.STRING, + number=6, + ) + slp_name: str = proto.Field( + proto.STRING, + number=7, + ) + + +class DataSourceGcpResource(proto.Message): + r"""DataSourceGcpResource is used for protected resources that + are Google Cloud Resources. This name is easeier to understand + than GcpResourceDataSource or GcpDataSourceResource + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + compute_instance_datasource_properties (google.cloud.backupdr_v1beta.types.ComputeInstanceDataSourceProperties): + ComputeInstanceDataSourceProperties has a + subset of Compute Instance properties that are + useful at the Datasource level. + + This field is a member of `oneof`_ ``gcp_resource_properties``. + cloud_sql_instance_datasource_properties (google.cloud.backupdr_v1beta.types.CloudSqlInstanceDataSourceProperties): + Output only. + CloudSqlInstanceDataSourceProperties has a + subset of Cloud SQL Instance properties that are + useful at the Datasource level. + + This field is a member of `oneof`_ ``gcp_resource_properties``. + alloy_db_cluster_datasource_properties (google.cloud.backupdr_v1beta.types.AlloyDBClusterDataSourceProperties): + Output only. + AlloyDBClusterDataSourceProperties has a subset + of AlloyDB cluster properties that are useful at + the Datasource level. Currently none of its + child properties are auditable. If new auditable + properties are added, the AUDIT annotation + should be added. + + This field is a member of `oneof`_ ``gcp_resource_properties``. + disk_datasource_properties (google.cloud.backupdr_v1beta.types.DiskDataSourceProperties): + DiskDataSourceProperties has a subset of Disk + properties that are useful at the Datasource + level. + + This field is a member of `oneof`_ ``gcp_resource_properties``. + gcp_resourcename (str): + Output only. Full resource pathname URL of + the source Google Cloud resource. + location (str): + Location of the resource: + //"global"/"unspecified". + type_ (str): + The type of the Google Cloud resource. Use + the Unified Resource Type, eg. + compute.googleapis.com/Instance. + """ + + compute_instance_datasource_properties: backupvault_gce.ComputeInstanceDataSourceProperties = proto.Field( + proto.MESSAGE, + number=4, + oneof="gcp_resource_properties", + message=backupvault_gce.ComputeInstanceDataSourceProperties, + ) + cloud_sql_instance_datasource_properties: backupvault_cloudsql.CloudSqlInstanceDataSourceProperties = proto.Field( + proto.MESSAGE, + number=5, + oneof="gcp_resource_properties", + message=backupvault_cloudsql.CloudSqlInstanceDataSourceProperties, + ) + alloy_db_cluster_datasource_properties: backupvault_alloydb.AlloyDBClusterDataSourceProperties = proto.Field( + proto.MESSAGE, + number=6, + oneof="gcp_resource_properties", + message=backupvault_alloydb.AlloyDBClusterDataSourceProperties, + ) + disk_datasource_properties: backupvault_disk.DiskDataSourceProperties = proto.Field( + proto.MESSAGE, + number=7, + oneof="gcp_resource_properties", + message=backupvault_disk.DiskDataSourceProperties, + ) + gcp_resourcename: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DataSourceBackupApplianceApplication(proto.Message): + r"""BackupApplianceApplication describes a Source Resource when + it is an application backed up by a BackupAppliance. + + Attributes: + application_name (str): + The name of the Application as known to the + Backup Appliance. + backup_appliance (str): + Appliance name. + appliance_id (int): + Appliance Id of the Backup Appliance. + type_ (str): + The type of the application. e.g. VMBackup + application_id (int): + The appid field of the application within the + Backup Appliance. + hostname (str): + Hostname of the host where the application is + running. + host_id (int): + Hostid of the application host. + """ + + application_name: str = proto.Field( + proto.STRING, + number=1, + ) + backup_appliance: str = proto.Field( + proto.STRING, + number=2, + ) + appliance_id: int = proto.Field( + proto.INT64, + number=3, + ) + type_: str = proto.Field( + proto.STRING, + number=4, + ) + application_id: int = proto.Field( + proto.INT64, + number=8, + ) + hostname: str = proto.Field( + proto.STRING, + number=6, + ) + host_id: int = proto.Field( + proto.INT64, + number=7, + ) + + +class ServiceLockInfo(proto.Message): + r"""ServiceLockInfo represents the details of a lock taken by the + service on a Backup resource. + + Attributes: + operation (str): + Output only. The name of the operation that + created this lock. The lock will automatically + be released when the operation completes. + """ + + operation: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BackupApplianceLockInfo(proto.Message): + r"""BackupApplianceLockInfo contains metadata about the + backupappliance that created the lock. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + job_name (str): + The job name on the backup/recovery appliance + that created this lock. + + This field is a member of `oneof`_ ``lock_source``. + backup_image (str): + The image name that depends on this Backup. + + This field is a member of `oneof`_ ``lock_source``. + sla_id (int): + The SLA on the backup/recovery appliance that + owns the lock. + + This field is a member of `oneof`_ ``lock_source``. + backup_appliance_id (int): + Required. The ID of the backup/recovery + appliance that created this lock. + backup_appliance_name (str): + Required. The name of the backup/recovery + appliance that created this lock. + lock_reason (str): + Required. The reason for the lock: e.g. + MOUNT/RESTORE/BACKUP/etc. The value of this + string is only meaningful to the client and it + is not interpreted by the BackupVault service. + """ + + job_name: str = proto.Field( + proto.STRING, + number=6, + oneof="lock_source", + ) + backup_image: str = proto.Field( + proto.STRING, + number=7, + oneof="lock_source", + ) + sla_id: int = proto.Field( + proto.INT64, + number=8, + oneof="lock_source", + ) + backup_appliance_id: int = proto.Field( + proto.INT64, + number=1, + ) + backup_appliance_name: str = proto.Field( + proto.STRING, + number=2, + ) + lock_reason: str = proto.Field( + proto.STRING, + number=5, + ) + + +class BackupLock(proto.Message): + r"""BackupLock represents a single lock on a Backup resource. An + unexpired lock on a Backup prevents the Backup from being + deleted. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_appliance_lock_info (google.cloud.backupdr_v1beta.types.BackupApplianceLockInfo): + If the client is a backup and recovery + appliance, this contains metadata about why the + lock exists. + + This field is a member of `oneof`_ ``ClientLockInfo``. + service_lock_info (google.cloud.backupdr_v1beta.types.ServiceLockInfo): + Output only. Contains metadata about the lock + exist for Google Cloud native backups. + + This field is a member of `oneof`_ ``ClientLockInfo``. + lock_until_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time after which this lock is + not considered valid and will no longer protect + the Backup from deletion. + """ + + backup_appliance_lock_info: "BackupApplianceLockInfo" = proto.Field( + proto.MESSAGE, + number=3, + oneof="ClientLockInfo", + message="BackupApplianceLockInfo", + ) + service_lock_info: "ServiceLockInfo" = proto.Field( + proto.MESSAGE, + number=4, + oneof="ClientLockInfo", + message="ServiceLockInfo", + ) + lock_until_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +class Backup(proto.Message): + r"""Message describing a Backup object. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + compute_instance_backup_properties (google.cloud.backupdr_v1beta.types.ComputeInstanceBackupProperties): + Output only. Compute Engine specific backup + properties. + + This field is a member of `oneof`_ ``backup_properties``. + cloud_sql_instance_backup_properties (google.cloud.backupdr_v1beta.types.CloudSqlInstanceBackupProperties): + Output only. Cloud SQL specific backup + properties. + + This field is a member of `oneof`_ ``backup_properties``. + backup_appliance_backup_properties (google.cloud.backupdr_v1beta.types.BackupApplianceBackupProperties): + Output only. Backup Appliance specific backup + properties. + + This field is a member of `oneof`_ ``backup_properties``. + alloy_db_backup_properties (google.cloud.backupdr_v1beta.types.AlloyDbClusterBackupProperties): + Output only. AlloyDB specific backup + properties. + + This field is a member of `oneof`_ ``backup_properties``. + disk_backup_properties (google.cloud.backupdr_v1beta.types.DiskBackupProperties): + Output only. Disk specific backup properties. + + This field is a member of `oneof`_ ``backup_properties``. + gcp_backup_plan_info (google.cloud.backupdr_v1beta.types.Backup.GCPBackupPlanInfo): + Output only. Configuration for a Google Cloud + resource. + + This field is a member of `oneof`_ ``plan_info``. + gcp_resource (google.cloud.backupdr_v1beta.types.BackupGcpResource): + Output only. Unique identifier of the GCP + resource that is being backed up. + + This field is a member of `oneof`_ ``source_resource``. + name (str): + Output only. Identifier. Name of the backup to create. It + must have the + format\ ``"projects//locations//backupVaults//dataSources/{datasource}/backups/{backup}"``. + ``{backup}`` cannot be changed after creation. It must be + between 3-63 characters long and must be unique within the + datasource. + description (str): + Output only. The description of the Backup + instance (2048 characters or less). + + This field is a member of `oneof`_ ``_description``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + created. + + This field is a member of `oneof`_ ``_create_time``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + updated. + + This field is a member of `oneof`_ ``_update_time``. + labels (MutableMapping[str, str]): + Optional. Resource labels to represent user + provided metadata. No labels currently defined. + enforced_retention_end_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The backup can not be deleted + before this time. + + This field is a member of `oneof`_ ``_enforced_retention_end_time``. + backup_retention_inheritance (google.cloud.backupdr_v1beta.types.BackupVault.BackupRetentionInheritance): + Output only. Setting for how the enforced + retention end time is inherited. This value is + copied from this backup's BackupVault. + + This field is a member of `oneof`_ ``_backup_retention_inheritance``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. When this backup is automatically + expired. + + This field is a member of `oneof`_ ``_expire_time``. + consistency_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The point in time when this + backup was captured from the source. + + This field is a member of `oneof`_ ``_consistency_time``. + etag (str): + Optional. Server specified ETag to prevent + updates from overwriting each other. + + This field is a member of `oneof`_ ``_etag``. + state (google.cloud.backupdr_v1beta.types.Backup.State): + Output only. The Backup resource instance + state. + service_locks (MutableSequence[google.cloud.backupdr_v1beta.types.BackupLock]): + Output only. The list of BackupLocks taken by + the service to prevent the deletion of the + backup. + backup_appliance_locks (MutableSequence[google.cloud.backupdr_v1beta.types.BackupLock]): + Optional. The list of BackupLocks taken by + the accessor Backup Appliance. + backup_type (google.cloud.backupdr_v1beta.types.Backup.BackupType): + Output only. Type of the backup, unspecified, + scheduled or ondemand. + resource_size_bytes (int): + Output only. source resource size in bytes at + the time of the backup. + satisfies_pzs (bool): + Optional. Output only. Reserved for future + use. + + This field is a member of `oneof`_ ``_satisfies_pzs``. + satisfies_pzi (bool): + Optional. Output only. Reserved for future + use. + + This field is a member of `oneof`_ ``_satisfies_pzi``. + kms_key_versions (MutableSequence[str]): + Optional. Output only. The list of KMS key + versions used to encrypt the backup. + """ + + class State(proto.Enum): + r"""Holds the state of the backup resource. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The backup is being created. + ACTIVE (2): + The backup has been created and is fully + usable. + DELETING (3): + The backup is being deleted. + ERROR (4): + The backup is experiencing an issue and might + be unusable. + UPLOADING (5): + The backup is being uploaded. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + ERROR = 4 + UPLOADING = 5 + + class BackupType(proto.Enum): + r"""Type of the backup, scheduled or ondemand. + + Values: + BACKUP_TYPE_UNSPECIFIED (0): + Backup type is unspecified. + SCHEDULED (1): + Scheduled backup. + ON_DEMAND (2): + On demand backup. + ON_DEMAND_OPERATIONAL (3): + Operational backup. + """ + + BACKUP_TYPE_UNSPECIFIED = 0 + SCHEDULED = 1 + ON_DEMAND = 2 + ON_DEMAND_OPERATIONAL = 3 + + class GCPBackupPlanInfo(proto.Message): + r"""GCPBackupPlanInfo captures the plan configuration details of + Google Cloud resources at the time of backup. + + Attributes: + backup_plan (str): + Resource name of backup plan by which + workload is protected at the time of the backup. + Format: + + projects/{project}/locations/{location}/backupPlans/{backupPlanId} + backup_plan_rule_id (str): + The rule id of the backup plan which + triggered this backup in case of scheduled + backup or used for + backup_plan_revision_name (str): + Resource name of the backup plan revision + which triggered this backup in case of scheduled + backup or used for on demand backup. Format: + + projects/{project}/locations/{location}/backupPlans/{backupPlanId}/revisions/{revisionId} + backup_plan_revision_id (str): + The user friendly id of the backup plan + revision which triggered this backup in case of + scheduled backup or used for on demand backup. + """ + + backup_plan: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan_rule_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup_plan_revision_name: str = proto.Field( + proto.STRING, + number=3, + ) + backup_plan_revision_id: str = proto.Field( + proto.STRING, + number=4, + ) + + compute_instance_backup_properties: backupvault_gce.ComputeInstanceBackupProperties = proto.Field( + proto.MESSAGE, + number=19, + oneof="backup_properties", + message=backupvault_gce.ComputeInstanceBackupProperties, + ) + cloud_sql_instance_backup_properties: backupvault_cloudsql.CloudSqlInstanceBackupProperties = proto.Field( + proto.MESSAGE, + number=26, + oneof="backup_properties", + message=backupvault_cloudsql.CloudSqlInstanceBackupProperties, + ) + backup_appliance_backup_properties: backupvault_ba.BackupApplianceBackupProperties = proto.Field( + proto.MESSAGE, + number=21, + oneof="backup_properties", + message=backupvault_ba.BackupApplianceBackupProperties, + ) + alloy_db_backup_properties: backupvault_alloydb.AlloyDbClusterBackupProperties = ( + proto.Field( + proto.MESSAGE, + number=27, + oneof="backup_properties", + message=backupvault_alloydb.AlloyDbClusterBackupProperties, + ) + ) + disk_backup_properties: backupvault_disk.DiskBackupProperties = proto.Field( + proto.MESSAGE, + number=28, + oneof="backup_properties", + message=backupvault_disk.DiskBackupProperties, + ) + gcp_backup_plan_info: GCPBackupPlanInfo = proto.Field( + proto.MESSAGE, + number=22, + oneof="plan_info", + message=GCPBackupPlanInfo, + ) + gcp_resource: "BackupGcpResource" = proto.Field( + proto.MESSAGE, + number=31, + oneof="source_resource", + message="BackupGcpResource", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + enforced_retention_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=timestamp_pb2.Timestamp, + ) + backup_retention_inheritance: "BackupVault.BackupRetentionInheritance" = ( + proto.Field( + proto.ENUM, + number=30, + optional=True, + enum="BackupVault.BackupRetentionInheritance", + ) + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message=timestamp_pb2.Timestamp, + ) + consistency_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + optional=True, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + state: State = proto.Field( + proto.ENUM, + number=15, + enum=State, + ) + service_locks: MutableSequence["BackupLock"] = proto.RepeatedField( + proto.MESSAGE, + number=17, + message="BackupLock", + ) + backup_appliance_locks: MutableSequence["BackupLock"] = proto.RepeatedField( + proto.MESSAGE, + number=18, + message="BackupLock", + ) + backup_type: BackupType = proto.Field( + proto.ENUM, + number=20, + enum=BackupType, + ) + resource_size_bytes: int = proto.Field( + proto.INT64, + number=23, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=24, + optional=True, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=25, + optional=True, + ) + kms_key_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=33, + ) + + +class CreateBackupVaultRequest(proto.Message): + r"""Message for creating a BackupVault. + + Attributes: + parent (str): + Required. Value for parent. + backup_vault_id (str): + Required. ID of the requesting object If auto-generating ID + server-side, remove this field and backup_vault_id from the + method_signature of Create RPC + backup_vault (google.cloud.backupdr_v1beta.types.BackupVault): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. Only validate the request, but do + not perform mutations. The default is 'false'. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + backup_vault_id: str = proto.Field( + proto.STRING, + number=2, + ) + backup_vault: "BackupVault" = proto.Field( + proto.MESSAGE, + number=3, + message="BackupVault", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class ListBackupVaultsRequest(proto.Message): + r"""Request message for listing backupvault stores. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + backupvault stores information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. To retrieve backupvault stores + for all locations, use "-" for the '{location}' value. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + view (google.cloud.backupdr_v1beta.types.BackupVaultView): + Optional. Reserved for future use to provide + a BASIC & FULL view of Backup Vault. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + view: "BackupVaultView" = proto.Field( + proto.ENUM, + number=6, + enum="BackupVaultView", + ) + + +class ListBackupVaultsResponse(proto.Message): + r"""Response message for listing BackupVaults. + + Attributes: + backup_vaults (MutableSequence[google.cloud.backupdr_v1beta.types.BackupVault]): + The list of BackupVault instances in the + project for the specified location. + + If the '{location}' value in the request is "-", + the response contains a list of instances from + all locations. In case any location is + unreachable, the response will only return + backup vaults in reachable locations and the + 'unreachable' field will be populated with a + list of unreachable locations. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backup_vaults: MutableSequence["BackupVault"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupVault", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class FetchUsableBackupVaultsRequest(proto.Message): + r"""Request message for fetching usable BackupVaults. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + backupvault stores information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. To retrieve backupvault stores + for all locations, use "-" for the '{location}' value. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class FetchUsableBackupVaultsResponse(proto.Message): + r"""Response message for fetching usable BackupVaults. + + Attributes: + backup_vaults (MutableSequence[google.cloud.backupdr_v1beta.types.BackupVault]): + The list of BackupVault instances in the + project for the specified location. + + If the '{location}' value in the request is "-", + the response contains a list of instances from + all locations. In case any location is + unreachable, the response will only return + backup vaults in reachable locations and the + 'unreachable' field will be populated with a + list of unreachable locations. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backup_vaults: MutableSequence["BackupVault"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupVault", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class FetchBackupsForResourceTypeRequest(proto.Message): + r"""Request for the FetchBackupsForResourceType method. + + Attributes: + parent (str): + Required. Datasources are the parent resource + for the backups. Format: + + projects/{project}/locations/{location}/backupVaults/{backupVaultId}/dataSources/{datasourceId} + resource_type (str): + Required. The type of the GCP resource. + Ex: sqladmin.googleapis.com/Instance + page_size (int): + Optional. The maximum number of Backups to + return. The service may return fewer than this + value. If unspecified, at most 50 Backups will + be returned. The maximum value is 100; values + above 100 will be coerced to 100. + page_token (str): + Optional. A page token, received from a previous call of + ``FetchBackupsForResourceType``. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``FetchBackupsForResourceType`` must match the call that + provided the page token. + filter (str): + Optional. A filter expression that filters the results + fetched in the response. The expression must specify the + field name, a comparison operator, and the value that you + want to use for filtering. Supported fields: + + - name + - state + - backup_type + - create_time + - expire_time + - enforced_retention_end_time + - gcp_backup_plan_info.backup_plan + - cloud_sql_instance_backup_properties.instance_tier + - cloud_sql_instance_backup_properties.database_installed_version + order_by (str): + Optional. A comma-separated list of fields to order by, + sorted in ascending order. Use "desc" after a field name for + descending. + + Supported fields: + + - name + view (google.cloud.backupdr_v1beta.types.BackupView): + Optional. This parameter is used to specify + the view of the backup. If not specified, the + default view is BASIC. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + view: "BackupView" = proto.Field( + proto.ENUM, + number=7, + enum="BackupView", + ) + + +class FetchBackupsForResourceTypeResponse(proto.Message): + r"""Response for the FetchBackupsForResourceType method. + + Attributes: + backups (MutableSequence[google.cloud.backupdr_v1beta.types.Backup]): + The Backups from the specified parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence["Backup"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Backup", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetBackupVaultRequest(proto.Message): + r"""Request message for getting a BackupVault. + + Attributes: + name (str): + Required. Name of the backupvault store resource name, in + the format + 'projects/{project_id}/locations/{location}/backupVaults/{resource_name}' + view (google.cloud.backupdr_v1beta.types.BackupVaultView): + Optional. Reserved for future use to provide + a BASIC & FULL view of Backup Vault + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: "BackupVaultView" = proto.Field( + proto.ENUM, + number=2, + enum="BackupVaultView", + ) + + +class UpdateBackupVaultRequest(proto.Message): + r"""Request message for updating a BackupVault. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the BackupVault resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then the request will fail. + backup_vault (google.cloud.backupdr_v1beta.types.BackupVault): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. Only validate the request, but do + not perform mutations. The default is 'false'. + force (bool): + Optional. If set to true, will not check plan + duration against backup vault enforcement + duration. + force_update_access_restriction (bool): + Optional. If set to true, we will force + update access restriction even if some non + compliant data sources are present. The default + is 'false'. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + backup_vault: "BackupVault" = proto.Field( + proto.MESSAGE, + number=2, + message="BackupVault", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + force: bool = proto.Field( + proto.BOOL, + number=5, + ) + force_update_access_restriction: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class DeleteBackupVaultRequest(proto.Message): + r"""Message for deleting a BackupVault. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + force (bool): + Optional. If set to true, any data source + from this backup vault will also be deleted. + etag (str): + The current etag of the backup vault. + If an etag is provided and does not match the + current etag of the connection, deletion will be + blocked. + validate_only (bool): + Optional. Only validate the request, but do + not perform mutations. The default is 'false'. + allow_missing (bool): + Optional. If true and the BackupVault is not + found, the request will succeed but no action + will be taken. + ignore_backup_plan_references (bool): + Optional. If set to true, backupvault + deletion will proceed even if there are backup + plans referencing the backupvault. The default + is 'false'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=6, + ) + ignore_backup_plan_references: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class ListDataSourcesRequest(proto.Message): + r"""Request message for listing DataSources. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + data sources information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. To retrieve data sources for + all locations, use "-" for the '{location}' value. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListDataSourcesResponse(proto.Message): + r"""Response message for listing DataSources. + + Attributes: + data_sources (MutableSequence[google.cloud.backupdr_v1beta.types.DataSource]): + The list of DataSource instances in the + project for the specified location. + + If the '{location}' value in the request is "-", + the response contains a list of instances from + all locations. In case any location is + unreachable, the response will only return data + sources in reachable locations and the + 'unreachable' field will be populated with a + list of unreachable locations. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + data_sources: MutableSequence["DataSource"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="DataSource", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetDataSourceRequest(proto.Message): + r"""Request message for getting a DataSource instance. + + Attributes: + name (str): + Required. Name of the data source resource name, in the + format + 'projects/{project_id}/locations/{location}/backupVaults/{resource_name}/dataSource/{resource_name}' + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataSourceRequest(proto.Message): + r"""Request message for updating a data source instance. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the DataSource resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then the request will fail. + data_source (google.cloud.backupdr_v1beta.types.DataSource): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + allow_missing (bool): + Optional. Enable upsert. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + data_source: "DataSource" = proto.Field( + proto.MESSAGE, + number=2, + message="DataSource", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListBackupsRequest(proto.Message): + r"""Request message for listing Backups. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + backup information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. To retrieve data sources for + all locations, use "-" for the '{location}' value. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + view (google.cloud.backupdr_v1beta.types.BackupView): + Optional. Reserved for future use to provide + a BASIC & FULL view of Backup resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + view: "BackupView" = proto.Field( + proto.ENUM, + number=6, + enum="BackupView", + ) + + +class ListBackupsResponse(proto.Message): + r"""Response message for listing Backups. + + Attributes: + backups (MutableSequence[google.cloud.backupdr_v1beta.types.Backup]): + The list of Backup instances in the project + for the specified location. + + If the '{location}' value in the request is "-", + the response contains a list of instances from + all locations. In case any location is + unreachable, the response will only return data + sources in reachable locations and the + 'unreachable' field will be populated with a + list of unreachable locations. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence["Backup"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Backup", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetBackupRequest(proto.Message): + r"""Request message for getting a Backup. + + Attributes: + name (str): + Required. Name of the data source resource name, in the + format + 'projects/{project_id}/locations/{location}/backupVaults/{backupVault}/dataSources/{datasource}/backups/{backup}' + view (google.cloud.backupdr_v1beta.types.BackupView): + Optional. Reserved for future use to provide + a BASIC & FULL view of Backup resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: "BackupView" = proto.Field( + proto.ENUM, + number=2, + enum="BackupView", + ) + + +class UpdateBackupRequest(proto.Message): + r"""Request message for updating a Backup. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Backup resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field will be overwritten if it is + in the mask. If the user does not provide a mask then the + request will fail. + backup (google.cloud.backupdr_v1beta.types.Backup): + Required. The resource being updated + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + backup: "Backup" = proto.Field( + proto.MESSAGE, + number=2, + message="Backup", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Message for deleting a Backup. + + Attributes: + name (str): + Required. Name of the resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RestoreBackupRequest(proto.Message): + r"""Request message for restoring from a Backup. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + compute_instance_target_environment (google.cloud.backupdr_v1beta.types.ComputeInstanceTargetEnvironment): + Compute Engine target environment to be used + during restore. + + This field is a member of `oneof`_ ``target_environment``. + disk_target_environment (google.cloud.backupdr_v1beta.types.DiskTargetEnvironment): + Disk target environment to be used during + restore. + + This field is a member of `oneof`_ ``target_environment``. + region_disk_target_environment (google.cloud.backupdr_v1beta.types.RegionDiskTargetEnvironment): + Region disk target environment to be used + during restore. + + This field is a member of `oneof`_ ``target_environment``. + compute_instance_restore_properties (google.cloud.backupdr_v1beta.types.ComputeInstanceRestoreProperties): + Compute Engine instance properties to be + overridden during restore. + + This field is a member of `oneof`_ ``instance_properties``. + disk_restore_properties (google.cloud.backupdr_v1beta.types.DiskRestoreProperties): + Disk properties to be overridden during + restore. + + This field is a member of `oneof`_ ``instance_properties``. + name (str): + Required. The resource name of the Backup instance, in the + format + 'projects/*/locations/*/backupVaults/*/dataSources/*/backups/'. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + clear_overrides_field_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A field mask used to clear server-side default + values for fields within the ``instance_properties`` oneof. + + When a field in this mask is cleared, the server will not + apply its default logic (like inheriting a value from the + source) for that field. + + The most common current use case is clearing default + encryption keys. + + Examples of field mask paths: + + - Compute Instance Disks: + ``compute_instance_restore_properties.disks.*.disk_encryption_key`` + - Single Disk: + ``disk_restore_properties.disk_encryption_key`` + + This field is a member of `oneof`_ ``_clear_overrides_field_mask``. + """ + + compute_instance_target_environment: backupvault_gce.ComputeInstanceTargetEnvironment = proto.Field( + proto.MESSAGE, + number=3, + oneof="target_environment", + message=backupvault_gce.ComputeInstanceTargetEnvironment, + ) + disk_target_environment: backupvault_disk.DiskTargetEnvironment = proto.Field( + proto.MESSAGE, + number=5, + oneof="target_environment", + message=backupvault_disk.DiskTargetEnvironment, + ) + region_disk_target_environment: backupvault_disk.RegionDiskTargetEnvironment = ( + proto.Field( + proto.MESSAGE, + number=6, + oneof="target_environment", + message=backupvault_disk.RegionDiskTargetEnvironment, + ) + ) + compute_instance_restore_properties: backupvault_gce.ComputeInstanceRestoreProperties = proto.Field( + proto.MESSAGE, + number=4, + oneof="instance_properties", + message=backupvault_gce.ComputeInstanceRestoreProperties, + ) + disk_restore_properties: backupvault_disk.DiskRestoreProperties = proto.Field( + proto.MESSAGE, + number=7, + oneof="instance_properties", + message=backupvault_disk.DiskRestoreProperties, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + clear_overrides_field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message=field_mask_pb2.FieldMask, + ) + + +class RestoreBackupResponse(proto.Message): + r"""Response message for restoring from a Backup. + + Attributes: + target_resource (google.cloud.backupdr_v1beta.types.TargetResource): + Details of the target resource + created/modified as part of restore. + """ + + target_resource: "TargetResource" = proto.Field( + proto.MESSAGE, + number=1, + message="TargetResource", + ) + + +class TargetResource(proto.Message): + r"""Details of the target resource created/modified as part of + restore. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcp_resource (google.cloud.backupdr_v1beta.types.GcpResource): + Details of the native Google Cloud resource + created as part of restore. + + This field is a member of `oneof`_ ``target_resource_info``. + """ + + gcp_resource: "GcpResource" = proto.Field( + proto.MESSAGE, + number=1, + oneof="target_resource_info", + message="GcpResource", + ) + + +class GcpResource(proto.Message): + r"""Minimum details to identify a Google Cloud resource + + Attributes: + gcp_resourcename (str): + Name of the Google Cloud resource. + location (str): + Location of the resource: + //"global"/"unspecified". + type_ (str): + Type of the resource. Use the Unified + Resource Type, eg. + compute.googleapis.com/Instance. + """ + + gcp_resourcename: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BackupGcpResource(proto.Message): + r"""Minimum details to identify a Google Cloud resource for a + backup. + + Attributes: + gcp_resourcename (str): + Name of the Google Cloud resource. + location (str): + Location of the resource: + //"global"/"unspecified". + type_ (str): + Type of the resource. Use the Unified + Resource Type, eg. + compute.googleapis.com/Instance. + """ + + gcp_resourcename: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_alloydb.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_alloydb.py new file mode 100644 index 000000000000..f40d9a8a3468 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_alloydb.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "AlloyDBClusterDataSourceProperties", + "AlloyDBClusterDataSourceReferenceProperties", + "AlloyDbPitrWindow", + "AlloyDbClusterBackupProperties", + "AlloyDBClusterBackupPlanAssociationProperties", + }, +) + + +class AlloyDBClusterDataSourceProperties(proto.Message): + r"""AlloyDBClusterDataSourceProperties represents the properties + of a AlloyDB cluster resource that are stored in the DataSource. + . + + Attributes: + name (str): + Output only. Name of the AlloyDB cluster + backed up by the datasource. + pitr_windows (MutableSequence[google.cloud.backupdr_v1beta.types.AlloyDbPitrWindow]): + Output only. Point in time recovery windows. + The order is guaranteed to be ascending by start + time. + cluster_uid (str): + Output only. The cluster UID of the AlloyDB + cluster backed up by the datasource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pitr_windows: MutableSequence["AlloyDbPitrWindow"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="AlloyDbPitrWindow", + ) + cluster_uid: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AlloyDBClusterDataSourceReferenceProperties(proto.Message): + r"""AlloyDBClusterDataSourceReferenceProperties represents the + properties of an AlloyDB cluster that are stored in the + DataSourceReference. + + Attributes: + name (str): + Output only. Name of the AlloyDB cluster + backed up by the datasource. Format: + + projects/{project}/locations/{location}/clusters/{cluster} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AlloyDbPitrWindow(proto.Message): + r"""Point in time recovery window for an AlloyDB cluster. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The start time of the PITR + window. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The end time of the PITR window. + It is not set if the corresponding Backup Plan + Association is active. + log_retention_days (int): + Output only. Log retention days for the PITR + window. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + log_retention_days: int = proto.Field( + proto.INT64, + number=3, + ) + + +class AlloyDbClusterBackupProperties(proto.Message): + r"""AlloyDbClusterBackupProperties represents AlloyDB cluster + backup properties. + . + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + An optional text description for the backup. + + This field is a member of `oneof`_ ``_description``. + stored_bytes (int): + Output only. Storage usage of this particular + backup + chain_id (str): + Output only. The chain id of this backup. + Backups belonging to the same chain are sharing + the same chain id. This property is calculated + and maintained by BackupDR. + database_version (str): + Output only. The PostgreSQL major version of + the AlloyDB cluster when the backup was taken. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + stored_bytes: int = proto.Field( + proto.INT64, + number=2, + ) + chain_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class AlloyDBClusterBackupPlanAssociationProperties(proto.Message): + r"""Properties for an AlloyDB cluster backup plan association. + + Attributes: + cluster_uid (str): + Output only. The cluster UID of the AlloyDB + cluster. + """ + + cluster_uid: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_ba.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_ba.py new file mode 100644 index 000000000000..228265f2307a --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_ba.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "BackupApplianceBackupProperties", + }, +) + + +class BackupApplianceBackupProperties(proto.Message): + r"""BackupApplianceBackupProperties represents BackupDR backup + appliance's properties. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + generation_id (int): + Output only. The numeric generation ID of the + backup (monotonically increasing). + + This field is a member of `oneof`_ ``_generation_id``. + finalize_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when this backup object + was finalized (if none, backup is not + finalized). + + This field is a member of `oneof`_ ``_finalize_time``. + recovery_range_start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The earliest timestamp of data + available in this Backup. + + This field is a member of `oneof`_ ``_recovery_range_start_time``. + recovery_range_end_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The latest timestamp of data + available in this Backup. + + This field is a member of `oneof`_ ``_recovery_range_end_time``. + """ + + generation_id: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + finalize_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=timestamp_pb2.Timestamp, + ) + recovery_range_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=timestamp_pb2.Timestamp, + ) + recovery_range_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_cloudsql.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_cloudsql.py new file mode 100644 index 000000000000..ad2c05e11608 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_cloudsql.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "CloudSqlInstanceDataSourceProperties", + "CloudSqlInstanceBackupProperties", + "CloudSqlInstanceDataSourceReferenceProperties", + "CloudSqlInstanceInitializationConfig", + "CloudSqlInstanceBackupPlanAssociationProperties", + }, +) + + +class CloudSqlInstanceDataSourceProperties(proto.Message): + r"""CloudSqlInstanceDataSourceProperties represents the + properties of a Cloud SQL resource that are stored in the + DataSource. + + Attributes: + name (str): + Output only. Name of the Cloud SQL instance + backed up by the datasource. Format: + + projects/{project}/instances/{instance} + database_installed_version (str): + Output only. The installed database version + of the Cloud SQL instance. + instance_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The instance creation timestamp. + instance_tier (str): + Output only. The tier (or machine type) for this instance. + Example: ``db-custom-1-3840`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + database_installed_version: str = proto.Field( + proto.STRING, + number=2, + ) + instance_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + instance_tier: str = proto.Field( + proto.STRING, + number=5, + ) + + +class CloudSqlInstanceBackupProperties(proto.Message): + r"""CloudSqlInstanceBackupProperties represents Cloud SQL + Instance Backup properties. + + Attributes: + database_installed_version (str): + Output only. The installed database version + of the Cloud SQL instance when the backup was + taken. + final_backup (bool): + Output only. Whether the backup is a final + backup. + source_instance (str): + Output only. The source instance of the + backup. Format: + + projects/{project}/instances/{instance} + instance_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The instance creation timestamp. + instance_tier (str): + Output only. The tier (or machine type) for this instance. + Example: ``db-custom-1-3840`` + instance_delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The instance delete timestamp. + """ + + database_installed_version: str = proto.Field( + proto.STRING, + number=2, + ) + final_backup: bool = proto.Field( + proto.BOOL, + number=3, + ) + source_instance: str = proto.Field( + proto.STRING, + number=4, + ) + instance_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + instance_tier: str = proto.Field( + proto.STRING, + number=6, + ) + instance_delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class CloudSqlInstanceDataSourceReferenceProperties(proto.Message): + r"""CloudSqlInstanceDataSourceReferenceProperties represents the + properties of a Cloud SQL resource that are stored in the + DataSourceReference. + + Attributes: + name (str): + Output only. Name of the Cloud SQL instance + backed up by the datasource. Format: + + projects/{project}/instances/{instance} + database_installed_version (str): + Output only. The installed database version + of the Cloud SQL instance. + instance_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The instance creation timestamp. + instance_tier (str): + Output only. The tier (or machine type) for this instance. + Example: ``db-custom-1-3840`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + database_installed_version: str = proto.Field( + proto.STRING, + number=2, + ) + instance_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + instance_tier: str = proto.Field( + proto.STRING, + number=5, + ) + + +class CloudSqlInstanceInitializationConfig(proto.Message): + r"""CloudSqlInstanceInitializationConfig contains the + configuration for initializing a Cloud SQL instance. + + Attributes: + edition (google.cloud.backupdr_v1beta.types.CloudSqlInstanceInitializationConfig.Edition): + Required. The edition of the Cloud SQL + instance. + """ + + class Edition(proto.Enum): + r"""The edition of the Cloud SQL instance. For details, see + https://cloud.google.com/sql/docs/editions-intro. + + Values: + EDITION_UNSPECIFIED (0): + Unspecified edition. + ENTERPRISE (1): + Enterprise edition. + ENTERPRISE_PLUS (2): + Enterprise Plus edition. + """ + + EDITION_UNSPECIFIED = 0 + ENTERPRISE = 1 + ENTERPRISE_PLUS = 2 + + edition: Edition = proto.Field( + proto.ENUM, + number=1, + enum=Edition, + ) + + +class CloudSqlInstanceBackupPlanAssociationProperties(proto.Message): + r"""Cloud SQL instance's BPA properties. + + Attributes: + instance_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + created. + """ + + instance_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_disk.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_disk.py new file mode 100644 index 000000000000..ab55c371b46e --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_disk.py @@ -0,0 +1,611 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.backupdr_v1beta.types import backupvault_gce + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "DiskTargetEnvironment", + "RegionDiskTargetEnvironment", + "DiskRestoreProperties", + "RestoreDiskFromInstanceOptions", + "DiskBackupProperties", + "DiskDataSourceProperties", + }, +) + + +class DiskTargetEnvironment(proto.Message): + r"""DiskTargetEnvironment represents the target environment for + the disk. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Required. Target project for the disk. + zone (str): + Required. Target zone for the disk. + use_project_service_account (bool): + Optional. Whether to use the project service + account for the disk restore. + + This field is a member of `oneof`_ ``_use_project_service_account``. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + zone: str = proto.Field( + proto.STRING, + number=2, + ) + use_project_service_account: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + + +class RegionDiskTargetEnvironment(proto.Message): + r"""RegionDiskTargetEnvironment represents the target environment + for the disk. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Required. Target project for the disk. + region (str): + Required. Target region for the disk. + replica_zones (MutableSequence[str]): + Required. Target URLs of the replica zones + for the disk. + use_project_service_account (bool): + Optional. Whether to use the project service + account for the disk restore. + + This field is a member of `oneof`_ ``_use_project_service_account``. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + region: str = proto.Field( + proto.STRING, + number=2, + ) + replica_zones: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + use_project_service_account: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class DiskRestoreProperties(proto.Message): + r"""DiskRestoreProperties represents the properties of a Disk + restore. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_backup_source (google.cloud.backupdr_v1beta.types.RestoreDiskFromInstanceOptions): + Options for creating a disk from a source + Compute Instance backup. + + This field is a member of `oneof`_ ``source_options``. + name (str): + Required. Name of the disk. + + This field is a member of `oneof`_ ``_name``. + description (str): + Optional. An optional description of this + resource. Provide this property when you create + the resource. + + This field is a member of `oneof`_ ``_description``. + size_gb (int): + Required. The size of the disk in GB. + + This field is a member of `oneof`_ ``_size_gb``. + licenses (MutableSequence[str]): + Optional. A list of publicly available + licenses that are applicable to this backup. + This is applicable if the original image had + licenses attached, e.g. Windows image + guest_os_feature (MutableSequence[google.cloud.backupdr_v1beta.types.GuestOsFeature]): + Optional. A list of features to enable in the + guest operating system. This is applicable only + for bootable images. + disk_encryption_key (google.cloud.backupdr_v1beta.types.CustomerEncryptionKey): + Optional. Encrypts the disk using a + customer-supplied encryption key or a + customer-managed encryption key. + + This field is a member of `oneof`_ ``_disk_encryption_key``. + physical_block_size_bytes (int): + Optional. Physical block size of the + persistent disk, in bytes. If not present in a + request, a default value is used. Currently, the + supported size is 4096. + + This field is a member of `oneof`_ ``_physical_block_size_bytes``. + provisioned_iops (int): + Optional. Indicates how many IOPS to + provision for the disk. This sets the number of + I/O operations per second that the disk can + handle. + + This field is a member of `oneof`_ ``_provisioned_iops``. + provisioned_throughput (int): + Optional. Indicates how much throughput to + provision for the disk. This sets the number of + throughput MB per second that the disk can + handle. + + This field is a member of `oneof`_ ``_provisioned_throughput``. + enable_confidential_compute (bool): + Optional. Indicates whether this disk is + using confidential compute mode. Encryption with + a Cloud KMS key is required to enable this + option. + + This field is a member of `oneof`_ ``_enable_confidential_compute``. + storage_pool (str): + Optional. The storage pool in which the new + disk is created. You can provide this as a + partial or full URL to the resource. + + This field is a member of `oneof`_ ``_storage_pool``. + access_mode (google.cloud.backupdr_v1beta.types.DiskRestoreProperties.AccessMode): + Optional. The access mode of the disk. + + This field is a member of `oneof`_ ``_access_mode``. + architecture (google.cloud.backupdr_v1beta.types.DiskRestoreProperties.Architecture): + Optional. The architecture of the source disk. Valid values + are ARM64 or X86_64. + + This field is a member of `oneof`_ ``_architecture``. + resource_policy (MutableSequence[str]): + Optional. Resource policies applied to this + disk. + type_ (str): + Required. URL of the disk type resource + describing which disk type to use to create the + disk. + + This field is a member of `oneof`_ ``_type``. + labels (MutableMapping[str, str]): + Optional. Labels to apply to this disk. These + can be modified later using + setLabels method. Label values can + be empty. + resource_manager_tags (MutableMapping[str, str]): + Optional. Resource manager tags to be bound + to the disk. + """ + + class AccessMode(proto.Enum): + r"""The supported access modes of the disk. + + Values: + READ_WRITE_SINGLE (0): + The default AccessMode, means the disk can be + attached to single instance in RW mode. + READ_WRITE_MANY (1): + The AccessMode means the disk can be attached + to multiple instances in RW mode. + READ_ONLY_MANY (2): + The AccessMode means the disk can be attached + to multiple instances in RO mode. + """ + + READ_WRITE_SINGLE = 0 + READ_WRITE_MANY = 1 + READ_ONLY_MANY = 2 + + class Architecture(proto.Enum): + r"""Architecture of the source disk. + + Values: + ARCHITECTURE_UNSPECIFIED (0): + Default value. This value is unused. + X86_64 (1): + Disks with architecture X86_64 + ARM64 (2): + Disks with architecture ARM64 + """ + + ARCHITECTURE_UNSPECIFIED = 0 + X86_64 = 1 + ARM64 = 2 + + instance_backup_source: "RestoreDiskFromInstanceOptions" = proto.Field( + proto.MESSAGE, + number=19, + oneof="source_options", + message="RestoreDiskFromInstanceOptions", + ) + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + size_gb: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + licenses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + guest_os_feature: MutableSequence[backupvault_gce.GuestOsFeature] = ( + proto.RepeatedField( + proto.MESSAGE, + number=5, + message=backupvault_gce.GuestOsFeature, + ) + ) + disk_encryption_key: backupvault_gce.CustomerEncryptionKey = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=backupvault_gce.CustomerEncryptionKey, + ) + physical_block_size_bytes: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + provisioned_iops: int = proto.Field( + proto.INT64, + number=8, + optional=True, + ) + provisioned_throughput: int = proto.Field( + proto.INT64, + number=9, + optional=True, + ) + enable_confidential_compute: bool = proto.Field( + proto.BOOL, + number=10, + optional=True, + ) + storage_pool: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + access_mode: AccessMode = proto.Field( + proto.ENUM, + number=12, + optional=True, + enum=AccessMode, + ) + architecture: Architecture = proto.Field( + proto.ENUM, + number=14, + optional=True, + enum=Architecture, + ) + resource_policy: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + type_: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=17, + ) + resource_manager_tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + + +class RestoreDiskFromInstanceOptions(proto.Message): + r"""Options for creating a disk from a source Compute Instance + backup. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + source_device_name (str): + The device name of the disk to restore from + the VM backup. + + This field is a member of `oneof`_ ``source_disk``. + boot_disk (bool): + Set to true to restore the boot disk from the + instance backup. This field should only be set + to true if selected. + + This field is a member of `oneof`_ ``source_disk``. + """ + + source_device_name: str = proto.Field( + proto.STRING, + number=1, + oneof="source_disk", + ) + boot_disk: bool = proto.Field( + proto.BOOL, + number=2, + oneof="source_disk", + ) + + +class DiskBackupProperties(proto.Message): + r"""DiskBackupProperties represents the properties of a Disk + backup. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + A description of the source disk. + + This field is a member of `oneof`_ ``_description``. + licenses (MutableSequence[str]): + A list of publicly available licenses that + are applicable to this backup. This is + applicable if the original image had licenses + attached, e.g. Windows image. + guest_os_feature (MutableSequence[google.cloud.backupdr_v1beta.types.GuestOsFeature]): + A list of guest OS features that are + applicable to this backup. + architecture (google.cloud.backupdr_v1beta.types.DiskBackupProperties.Architecture): + The architecture of the source disk. Valid values are ARM64 + or X86_64. + + This field is a member of `oneof`_ ``_architecture``. + type_ (str): + The URL of the type of the disk. + + This field is a member of `oneof`_ ``_type``. + size_gb (int): + Size(in GB) of the source disk. + + This field is a member of `oneof`_ ``_size_gb``. + region (str): + Region and zone are mutually exclusive + fields. The URL of the region of the source + disk. + + This field is a member of `oneof`_ ``_region``. + zone (str): + The URL of the Zone where the source disk. + + This field is a member of `oneof`_ ``_zone``. + replica_zones (MutableSequence[str]): + The URL of the Zones where the source disk + should be replicated. + source_disk (str): + The source disk used to create this backup. + + This field is a member of `oneof`_ ``_source_disk``. + access_mode (str): + The access mode of the source disk. + + This field is a member of `oneof`_ ``_access_mode``. + provisioned_iops (int): + The number of IOPS provisioned for the source + disk. + + This field is a member of `oneof`_ ``_provisioned_iops``. + provisioned_throughput (int): + The number of throughput provisioned for the + source disk. + + This field is a member of `oneof`_ ``_provisioned_throughput``. + physical_block_size_bytes (int): + The physical block size of the source disk. + + This field is a member of `oneof`_ ``_physical_block_size_bytes``. + enable_confidential_compute (bool): + Indicates whether the source disk is using + confidential compute mode. + + This field is a member of `oneof`_ ``_enable_confidential_compute``. + storage_pool (str): + The storage pool of the source disk. + + This field is a member of `oneof`_ ``_storage_pool``. + labels (MutableMapping[str, str]): + The labels of the source disk. + guest_flush (bool): + Optional. Defines if the guest flush is + enabled for the source disk. Default value is + false. + """ + + class Architecture(proto.Enum): + r"""Architecture of the source disk. + + Values: + ARCHITECTURE_UNSPECIFIED (0): + Default value. This value is unused. + X86_64 (1): + Disks with architecture X86_64 + ARM64 (2): + Disks with architecture ARM64 + """ + + ARCHITECTURE_UNSPECIFIED = 0 + X86_64 = 1 + ARM64 = 2 + + description: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + licenses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + guest_os_feature: MutableSequence[backupvault_gce.GuestOsFeature] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message=backupvault_gce.GuestOsFeature, + ) + ) + architecture: Architecture = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=Architecture, + ) + type_: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + size_gb: int = proto.Field( + proto.INT64, + number=6, + optional=True, + ) + region: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + replica_zones: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + source_disk: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + access_mode: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + provisioned_iops: int = proto.Field( + proto.INT64, + number=12, + optional=True, + ) + provisioned_throughput: int = proto.Field( + proto.INT64, + number=13, + optional=True, + ) + physical_block_size_bytes: int = proto.Field( + proto.INT64, + number=14, + optional=True, + ) + enable_confidential_compute: bool = proto.Field( + proto.BOOL, + number=15, + optional=True, + ) + storage_pool: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=17, + ) + guest_flush: bool = proto.Field( + proto.BOOL, + number=18, + ) + + +class DiskDataSourceProperties(proto.Message): + r"""DiskDataSourceProperties represents the properties of a + Disk resource that are stored in the DataSource. + . + + Attributes: + name (str): + Name of the disk backed up by the datasource. + description (str): + The description of the disk. + type_ (str): + The type of the disk. + size_gb (int): + The size of the disk in GB. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + size_gb: int = proto.Field( + proto.INT64, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_gce.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_gce.py new file mode 100644 index 000000000000..42e0e1d76679 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault_gce.py @@ -0,0 +1,2037 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "KeyRevocationActionType", + "ComputeInstanceBackupProperties", + "ComputeInstanceRestoreProperties", + "ComputeInstanceTargetEnvironment", + "ComputeInstanceDataSourceProperties", + "AdvancedMachineFeatures", + "ConfidentialInstanceConfig", + "DisplayDevice", + "NetworkPerformanceConfig", + "InstanceParams", + "GuestOsFeature", + "AllocationAffinity", + "AcceleratorConfig", + "CustomerEncryptionKey", + "Entry", + "Metadata", + "NetworkInterface", + "AccessConfig", + "AliasIpRange", + "Scheduling", + "SchedulingDuration", + "ServiceAccount", + "Tags", + "AttachedDisk", + }, +) + + +class KeyRevocationActionType(proto.Enum): + r"""Specifies whether the virtual machine instance will be shut + down on key revocation. It is currently used in instance, + instance properties and GMI protos + + Values: + KEY_REVOCATION_ACTION_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + NONE (1): + Indicates user chose no operation. + STOP (2): + Indicates user chose to opt for VM shutdown + on key revocation. + """ + + KEY_REVOCATION_ACTION_TYPE_UNSPECIFIED = 0 + NONE = 1 + STOP = 2 + + +class ComputeInstanceBackupProperties(proto.Message): + r"""ComputeInstanceBackupProperties represents Compute Engine + instance backup properties. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + An optional text description for the + instances that are created from these + properties. + + This field is a member of `oneof`_ ``_description``. + tags (google.cloud.backupdr_v1beta.types.Tags): + A list of tags to apply to the instances that + are created from these properties. The tags + identify valid sources or targets for network + firewalls. The setTags method can modify this + list of tags. Each tag within the list must + comply with RFC1035 + (https://www.ietf.org/rfc/rfc1035.txt). + + This field is a member of `oneof`_ ``_tags``. + machine_type (str): + The machine type to use for instances that + are created from these properties. + + This field is a member of `oneof`_ ``_machine_type``. + can_ip_forward (bool): + Enables instances created based on these properties to send + packets with source IP addresses other than their own and + receive packets with destination IP addresses other than + their own. If these instances will be used as an IP gateway + or it will be set as the next-hop in a Route resource, + specify ``true``. If unsure, leave this set to ``false``. + See the + https://cloud.google.com/vpc/docs/using-routes#canipforward + documentation for more information. + + This field is a member of `oneof`_ ``_can_ip_forward``. + network_interface (MutableSequence[google.cloud.backupdr_v1beta.types.NetworkInterface]): + An array of network access configurations for + this interface. + disk (MutableSequence[google.cloud.backupdr_v1beta.types.AttachedDisk]): + An array of disks that are associated with + the instances that are created from these + properties. + metadata (google.cloud.backupdr_v1beta.types.Metadata): + The metadata key/value pairs to assign to + instances that are created from these + properties. These pairs can consist of custom + metadata or predefined keys. See + https://cloud.google.com/compute/docs/metadata/overview + for more information. + + This field is a member of `oneof`_ ``_metadata``. + service_account (MutableSequence[google.cloud.backupdr_v1beta.types.ServiceAccount]): + A list of service accounts with specified + scopes. Access tokens for these service accounts + are available to the instances that are created + from these properties. Use metadata queries to + obtain the access tokens for these instances. + scheduling (google.cloud.backupdr_v1beta.types.Scheduling): + Specifies the scheduling options for the + instances that are created from these + properties. + + This field is a member of `oneof`_ ``_scheduling``. + guest_accelerator (MutableSequence[google.cloud.backupdr_v1beta.types.AcceleratorConfig]): + A list of guest accelerator cards' type and + count to use for instances created from these + properties. + min_cpu_platform (str): + Minimum cpu/platform to be used by instances. The instance + may be scheduled on the specified or newer cpu/platform. + Applicable values are the friendly names of CPU platforms, + such as ``minCpuPlatform: Intel Haswell`` or + ``minCpuPlatform: Intel Sandy Bridge``. For more + information, read + https://cloud.google.com/compute/docs/instances/specify-min-cpu-platform. + + This field is a member of `oneof`_ ``_min_cpu_platform``. + key_revocation_action_type (google.cloud.backupdr_v1beta.types.KeyRevocationActionType): + KeyRevocationActionType of the instance. + Supported options are "STOP" and "NONE". The + default value is "NONE" if it is not specified. + + This field is a member of `oneof`_ ``_key_revocation_action_type``. + source_instance (str): + The source instance used to create this + backup. This can be a partial or full URL to the + resource. For example, the following are valid + values: + + -https://www.googleapis.com/compute/v1/projects/project/zones/zone/instances/instance + -projects/project/zones/zone/instances/instance + + This field is a member of `oneof`_ ``_source_instance``. + labels (MutableMapping[str, str]): + Labels to apply to instances that are created + from these properties. + guest_flush (bool): + Optional. Indicates whether to perform a + guest flush operation before taking a compute + backup. When set to false, the system will + create crash-consistent backups. Default value + is false. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + tags: "Tags" = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message="Tags", + ) + machine_type: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + can_ip_forward: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + network_interface: MutableSequence["NetworkInterface"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="NetworkInterface", + ) + disk: MutableSequence["AttachedDisk"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="AttachedDisk", + ) + metadata: "Metadata" = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message="Metadata", + ) + service_account: MutableSequence["ServiceAccount"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="ServiceAccount", + ) + scheduling: "Scheduling" = proto.Field( + proto.MESSAGE, + number=9, + optional=True, + message="Scheduling", + ) + guest_accelerator: MutableSequence["AcceleratorConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="AcceleratorConfig", + ) + min_cpu_platform: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + key_revocation_action_type: "KeyRevocationActionType" = proto.Field( + proto.ENUM, + number=12, + optional=True, + enum="KeyRevocationActionType", + ) + source_instance: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + guest_flush: bool = proto.Field( + proto.BOOL, + number=15, + ) + + +class ComputeInstanceRestoreProperties(proto.Message): + r"""ComputeInstanceRestoreProperties represents Compute Engine + instance properties to be overridden during restore. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the compute instance. + + This field is a member of `oneof`_ ``_name``. + advanced_machine_features (google.cloud.backupdr_v1beta.types.AdvancedMachineFeatures): + Optional. Controls for advanced + machine-related behavior features. + + This field is a member of `oneof`_ ``_advanced_machine_features``. + can_ip_forward (bool): + Optional. Allows this instance to send and + receive packets with non-matching destination or + source IPs. + + This field is a member of `oneof`_ ``_can_ip_forward``. + confidential_instance_config (google.cloud.backupdr_v1beta.types.ConfidentialInstanceConfig): + Optional. Controls Confidential compute + options on the instance + + This field is a member of `oneof`_ ``_confidential_instance_config``. + deletion_protection (bool): + Optional. Whether the resource should be + protected against deletion. + + This field is a member of `oneof`_ ``_deletion_protection``. + description (str): + Optional. An optional description of this + resource. Provide this property when you create + the resource. + + This field is a member of `oneof`_ ``_description``. + disks (MutableSequence[google.cloud.backupdr_v1beta.types.AttachedDisk]): + Optional. Array of disks associated with this + instance. Persistent disks must be created + before you can assign them. Source regional + persistent disks will be restored with default + replica zones if not specified. + display_device (google.cloud.backupdr_v1beta.types.DisplayDevice): + Optional. Enables display device for the + instance. + + This field is a member of `oneof`_ ``_display_device``. + guest_accelerators (MutableSequence[google.cloud.backupdr_v1beta.types.AcceleratorConfig]): + Optional. A list of the type and count of + accelerator cards attached to the instance. + hostname (str): + Optional. Specifies the hostname of the instance. The + specified hostname must be RFC1035 compliant. If hostname is + not specified, the default hostname is + [INSTANCE_NAME].c.[PROJECT_ID].internal when using the + global DNS, and + [INSTANCE_NAME].[ZONE].c.[PROJECT_ID].internal when using + zonal DNS. + + This field is a member of `oneof`_ ``_hostname``. + instance_encryption_key (google.cloud.backupdr_v1beta.types.CustomerEncryptionKey): + Optional. Encrypts suspended data for an + instance with a customer-managed encryption key. + + This field is a member of `oneof`_ ``_instance_encryption_key``. + key_revocation_action_type (google.cloud.backupdr_v1beta.types.KeyRevocationActionType): + Optional. KeyRevocationActionType of the + instance. + + This field is a member of `oneof`_ ``_key_revocation_action_type``. + labels (MutableMapping[str, str]): + Optional. Labels to apply to this instance. + machine_type (str): + Optional. Full or partial URL of the machine + type resource to use for this instance. + + This field is a member of `oneof`_ ``_machine_type``. + metadata (google.cloud.backupdr_v1beta.types.Metadata): + Optional. This includes custom metadata and + predefined keys. + + This field is a member of `oneof`_ ``_metadata``. + min_cpu_platform (str): + Optional. Minimum CPU platform to use for + this instance. + + This field is a member of `oneof`_ ``_min_cpu_platform``. + network_interfaces (MutableSequence[google.cloud.backupdr_v1beta.types.NetworkInterface]): + Optional. An array of network configurations + for this instance. These specify how interfaces + are configured to interact with other network + services, such as connecting to the internet. + Multiple interfaces are supported per instance. + Required to restore in different project or + region. + network_performance_config (google.cloud.backupdr_v1beta.types.NetworkPerformanceConfig): + Optional. Configure network performance such + as egress bandwidth tier. + + This field is a member of `oneof`_ ``_network_performance_config``. + params (google.cloud.backupdr_v1beta.types.InstanceParams): + Input only. Additional params passed with the + request, but not persisted as part of resource + payload. + + This field is a member of `oneof`_ ``_params``. + private_ipv6_google_access (google.cloud.backupdr_v1beta.types.ComputeInstanceRestoreProperties.InstancePrivateIpv6GoogleAccess): + Optional. The private IPv6 google access type for the VM. If + not specified, use INHERIT_FROM_SUBNETWORK as default. + + This field is a member of `oneof`_ ``_private_ipv6_google_access``. + allocation_affinity (google.cloud.backupdr_v1beta.types.AllocationAffinity): + Optional. Specifies the reservations that + this instance can consume from. + + This field is a member of `oneof`_ ``_allocation_affinity``. + resource_policies (MutableSequence[str]): + Optional. Resource policies applied to this + instance. By default, no resource policies will + be applied. + scheduling (google.cloud.backupdr_v1beta.types.Scheduling): + Optional. Sets the scheduling options for + this instance. + + This field is a member of `oneof`_ ``_scheduling``. + service_accounts (MutableSequence[google.cloud.backupdr_v1beta.types.ServiceAccount]): + Optional. A list of service accounts, with + their specified scopes, authorized for this + instance. Only one service account per VM + instance is supported. + tags (google.cloud.backupdr_v1beta.types.Tags): + Optional. Tags to apply to this instance. + Tags are used to identify valid sources or + targets for network firewalls and are specified + by the client during instance creation. + + This field is a member of `oneof`_ ``_tags``. + """ + + class InstancePrivateIpv6GoogleAccess(proto.Enum): + r"""The private IPv6 google access type for the VMs. + + Values: + INSTANCE_PRIVATE_IPV6_GOOGLE_ACCESS_UNSPECIFIED (0): + Default value. This value is unused. + INHERIT_FROM_SUBNETWORK (1): + Each network interface inherits + PrivateIpv6GoogleAccess from its subnetwork. + ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE (2): + Outbound private IPv6 access from VMs in this + subnet to Google services. If specified, the + subnetwork who is attached to the instance's + default network interface will be assigned an + internal IPv6 prefix if it doesn't have before. + ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE (3): + Bidirectional private IPv6 access to/from + Google services. If specified, the subnetwork + who is attached to the instance's default + network interface will be assigned an internal + IPv6 prefix if it doesn't have before. + """ + + INSTANCE_PRIVATE_IPV6_GOOGLE_ACCESS_UNSPECIFIED = 0 + INHERIT_FROM_SUBNETWORK = 1 + ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 2 + ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + advanced_machine_features: "AdvancedMachineFeatures" = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message="AdvancedMachineFeatures", + ) + can_ip_forward: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + confidential_instance_config: "ConfidentialInstanceConfig" = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message="ConfidentialInstanceConfig", + ) + deletion_protection: bool = proto.Field( + proto.BOOL, + number=5, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + disks: MutableSequence["AttachedDisk"] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="AttachedDisk", + ) + display_device: "DisplayDevice" = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message="DisplayDevice", + ) + guest_accelerators: MutableSequence["AcceleratorConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="AcceleratorConfig", + ) + hostname: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + instance_encryption_key: "CustomerEncryptionKey" = proto.Field( + proto.MESSAGE, + number=11, + optional=True, + message="CustomerEncryptionKey", + ) + key_revocation_action_type: "KeyRevocationActionType" = proto.Field( + proto.ENUM, + number=12, + optional=True, + enum="KeyRevocationActionType", + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + machine_type: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + metadata: "Metadata" = proto.Field( + proto.MESSAGE, + number=15, + optional=True, + message="Metadata", + ) + min_cpu_platform: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + network_interfaces: MutableSequence["NetworkInterface"] = proto.RepeatedField( + proto.MESSAGE, + number=17, + message="NetworkInterface", + ) + network_performance_config: "NetworkPerformanceConfig" = proto.Field( + proto.MESSAGE, + number=18, + optional=True, + message="NetworkPerformanceConfig", + ) + params: "InstanceParams" = proto.Field( + proto.MESSAGE, + number=19, + optional=True, + message="InstanceParams", + ) + private_ipv6_google_access: InstancePrivateIpv6GoogleAccess = proto.Field( + proto.ENUM, + number=20, + optional=True, + enum=InstancePrivateIpv6GoogleAccess, + ) + allocation_affinity: "AllocationAffinity" = proto.Field( + proto.MESSAGE, + number=21, + optional=True, + message="AllocationAffinity", + ) + resource_policies: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=22, + ) + scheduling: "Scheduling" = proto.Field( + proto.MESSAGE, + number=23, + optional=True, + message="Scheduling", + ) + service_accounts: MutableSequence["ServiceAccount"] = proto.RepeatedField( + proto.MESSAGE, + number=24, + message="ServiceAccount", + ) + tags: "Tags" = proto.Field( + proto.MESSAGE, + number=26, + optional=True, + message="Tags", + ) + + +class ComputeInstanceTargetEnvironment(proto.Message): + r"""ComputeInstanceTargetEnvironment represents Compute Engine + target environment to be used during restore. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Required. Target project for the Compute + Engine instance. + zone (str): + Required. The zone of the Compute Engine + instance. + use_project_service_account (bool): + Optional. Whether to use the project service + account for the Compute Engine instance restore. + + This field is a member of `oneof`_ ``_use_project_service_account``. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + zone: str = proto.Field( + proto.STRING, + number=2, + ) + use_project_service_account: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + + +class ComputeInstanceDataSourceProperties(proto.Message): + r"""ComputeInstanceDataSourceProperties represents the properties + of a ComputeEngine resource that are stored in the DataSource. + + Attributes: + name (str): + Name of the compute instance backed up by the + datasource. + description (str): + The description of the Compute Engine + instance. + machine_type (str): + The machine type of the instance. + total_disk_count (int): + The total number of disks attached to the + Instance. + total_disk_size_gb (int): + The sum of all the disk sizes. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + machine_type: str = proto.Field( + proto.STRING, + number=3, + ) + total_disk_count: int = proto.Field( + proto.INT64, + number=4, + ) + total_disk_size_gb: int = proto.Field( + proto.INT64, + number=5, + ) + + +class AdvancedMachineFeatures(proto.Message): + r"""Specifies options for controlling advanced machine features. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enable_nested_virtualization (bool): + Optional. Whether to enable nested + virtualization or not (default is false). + + This field is a member of `oneof`_ ``_enable_nested_virtualization``. + threads_per_core (int): + Optional. The number of threads per physical + core. To disable simultaneous multithreading + (SMT) set this to 1. If unset, the maximum + number of threads supported per core by the + underlying processor is assumed. + + This field is a member of `oneof`_ ``_threads_per_core``. + visible_core_count (int): + Optional. The number of physical cores to + expose to an instance. Multiply by the number of + threads per core to compute the total number of + virtual CPUs to expose to the instance. If + unset, the number of cores is inferred from the + instance's nominal CPU count and the underlying + platform's SMT width. + + This field is a member of `oneof`_ ``_visible_core_count``. + enable_uefi_networking (bool): + Optional. Whether to enable UEFI networking + for instance creation. + + This field is a member of `oneof`_ ``_enable_uefi_networking``. + """ + + enable_nested_virtualization: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + threads_per_core: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + visible_core_count: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + enable_uefi_networking: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + +class ConfidentialInstanceConfig(proto.Message): + r"""A set of Confidential Instance options. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enable_confidential_compute (bool): + Optional. Defines whether the instance should + have confidential compute enabled. + + This field is a member of `oneof`_ ``_enable_confidential_compute``. + """ + + enable_confidential_compute: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + +class DisplayDevice(proto.Message): + r"""A set of Display Device options + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enable_display (bool): + Optional. Enables display for the Compute + Engine VM + + This field is a member of `oneof`_ ``_enable_display``. + """ + + enable_display: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + +class NetworkPerformanceConfig(proto.Message): + r"""Network performance configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + total_egress_bandwidth_tier (google.cloud.backupdr_v1beta.types.NetworkPerformanceConfig.Tier): + Optional. The tier of the total egress + bandwidth. + + This field is a member of `oneof`_ ``_total_egress_bandwidth_tier``. + """ + + class Tier(proto.Enum): + r"""Network performance tier. + + Values: + TIER_UNSPECIFIED (0): + This value is unused. + DEFAULT (1): + Default network performance config. + TIER_1 (2): + Tier 1 network performance config. + """ + + TIER_UNSPECIFIED = 0 + DEFAULT = 1 + TIER_1 = 2 + + total_egress_bandwidth_tier: Tier = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=Tier, + ) + + +class InstanceParams(proto.Message): + r"""Additional instance params. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Optional. Resource manager tags to be bound + to the instance. + """ + + resource_manager_tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + + +class GuestOsFeature(proto.Message): + r"""Feature type of the Guest OS. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.cloud.backupdr_v1beta.types.GuestOsFeature.FeatureType): + The ID of a supported feature. + + This field is a member of `oneof`_ ``_type``. + """ + + class FeatureType(proto.Enum): + r"""List of the Feature Types. + + Values: + FEATURE_TYPE_UNSPECIFIED (0): + Default value, which is unused. + VIRTIO_SCSI_MULTIQUEUE (1): + VIRTIO_SCSI_MULTIQUEUE feature type. + WINDOWS (2): + WINDOWS feature type. + MULTI_IP_SUBNET (3): + MULTI_IP_SUBNET feature type. + UEFI_COMPATIBLE (4): + UEFI_COMPATIBLE feature type. + SECURE_BOOT (5): + SECURE_BOOT feature type. + GVNIC (6): + GVNIC feature type. + SEV_CAPABLE (7): + SEV_CAPABLE feature type. + BARE_METAL_LINUX_COMPATIBLE (8): + BARE_METAL_LINUX_COMPATIBLE feature type. + SUSPEND_RESUME_COMPATIBLE (9): + SUSPEND_RESUME_COMPATIBLE feature type. + SEV_LIVE_MIGRATABLE (10): + SEV_LIVE_MIGRATABLE feature type. + SEV_SNP_CAPABLE (11): + SEV_SNP_CAPABLE feature type. + TDX_CAPABLE (12): + TDX_CAPABLE feature type. + IDPF (13): + IDPF feature type. + SEV_LIVE_MIGRATABLE_V2 (14): + SEV_LIVE_MIGRATABLE_V2 feature type. + """ + + FEATURE_TYPE_UNSPECIFIED = 0 + VIRTIO_SCSI_MULTIQUEUE = 1 + WINDOWS = 2 + MULTI_IP_SUBNET = 3 + UEFI_COMPATIBLE = 4 + SECURE_BOOT = 5 + GVNIC = 6 + SEV_CAPABLE = 7 + BARE_METAL_LINUX_COMPATIBLE = 8 + SUSPEND_RESUME_COMPATIBLE = 9 + SEV_LIVE_MIGRATABLE = 10 + SEV_SNP_CAPABLE = 11 + TDX_CAPABLE = 12 + IDPF = 13 + SEV_LIVE_MIGRATABLE_V2 = 14 + + type_: FeatureType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=FeatureType, + ) + + +class AllocationAffinity(proto.Message): + r"""Specifies the reservations that this instance can consume + from. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + consume_allocation_type (google.cloud.backupdr_v1beta.types.AllocationAffinity.Type): + Optional. Specifies the type of reservation + from which this instance can consume + + This field is a member of `oneof`_ ``_consume_allocation_type``. + key (str): + Optional. Corresponds to the label key of a + reservation resource. + + This field is a member of `oneof`_ ``_key``. + values (MutableSequence[str]): + Optional. Corresponds to the label values of + a reservation resource. + """ + + class Type(proto.Enum): + r"""Indicates whether to consume from a reservation or not. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + NO_RESERVATION (1): + Do not consume from any allocated capacity. + ANY_RESERVATION (2): + Consume any allocation available. + SPECIFIC_RESERVATION (3): + Must consume from a specific reservation. + Must specify key value fields for specifying the + reservations. + """ + + TYPE_UNSPECIFIED = 0 + NO_RESERVATION = 1 + ANY_RESERVATION = 2 + SPECIFIC_RESERVATION = 3 + + consume_allocation_type: Type = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=Type, + ) + key: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class AcceleratorConfig(proto.Message): + r"""A specification of the type and number of accelerator cards + attached to the instance. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + accelerator_type (str): + Optional. Full or partial URL of the + accelerator type resource to attach to this + instance. + + This field is a member of `oneof`_ ``_accelerator_type``. + accelerator_count (int): + Optional. The number of the guest accelerator + cards exposed to this instance. + + This field is a member of `oneof`_ ``_accelerator_count``. + """ + + accelerator_type: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + accelerator_count: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class CustomerEncryptionKey(proto.Message): + r"""A customer-supplied encryption key. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + raw_key (str): + Optional. Specifies a 256-bit + customer-supplied encryption key. + + This field is a member of `oneof`_ ``key``. + rsa_encrypted_key (str): + Optional. RSA-wrapped 2048-bit + customer-supplied encryption key to either + encrypt or decrypt this resource. + + This field is a member of `oneof`_ ``key``. + kms_key_name (str): + Optional. The name of the encryption key that + is stored in Google Cloud KMS. + + This field is a member of `oneof`_ ``key``. + kms_key_service_account (str): + Optional. The service account being used for + the encryption request for the given KMS key. If + absent, the Compute Engine default service + account is used. + + This field is a member of `oneof`_ ``_kms_key_service_account``. + """ + + raw_key: str = proto.Field( + proto.STRING, + number=1, + oneof="key", + ) + rsa_encrypted_key: str = proto.Field( + proto.STRING, + number=2, + oneof="key", + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=3, + oneof="key", + ) + kms_key_service_account: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + + +class Entry(proto.Message): + r"""A key/value pair to be used for storing metadata. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + key (str): + Optional. Key for the metadata entry. + + This field is a member of `oneof`_ ``_key``. + value (str): + Optional. Value for the metadata entry. These + are free-form strings, and only have meaning as + interpreted by the image running in the + instance. The only restriction placed on values + is that their size must be less than or equal to + 262144 bytes (256 KiB). + + This field is a member of `oneof`_ ``_value``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + value: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + +class Metadata(proto.Message): + r"""A metadata key/value entry. + + Attributes: + items (MutableSequence[google.cloud.backupdr_v1beta.types.Entry]): + Optional. Array of key/value pairs. The total + size of all keys and values must be less than + 512 KB. + """ + + items: MutableSequence["Entry"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Entry", + ) + + +class NetworkInterface(proto.Message): + r"""A network interface resource attached to an instance. + s + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network (str): + Optional. URL of the VPC network resource for + this instance. + + This field is a member of `oneof`_ ``_network``. + subnetwork (str): + Optional. The URL of the Subnetwork resource + for this instance. + + This field is a member of `oneof`_ ``_subnetwork``. + ip_address (str): + Optional. An IPv4 internal IP address to + assign to the instance for this network + interface. If not specified by the user, an + unused internal IP is assigned by the system. + + This field is a member of `oneof`_ ``_ip_address``. + ipv6_address (str): + Optional. An IPv6 internal network address + for this network interface. To use a static + internal IP address, it must be unused and in + the same region as the instance's zone. If not + specified, Google Cloud will automatically + assign an internal IPv6 address from the + instance's subnetwork. + + This field is a member of `oneof`_ ``_ipv6_address``. + internal_ipv6_prefix_length (int): + Optional. The prefix length of the primary + internal IPv6 range. + + This field is a member of `oneof`_ ``_internal_ipv6_prefix_length``. + name (str): + Output only. [Output Only] The name of the network + interface, which is generated by the server. + + This field is a member of `oneof`_ ``_name``. + access_configs (MutableSequence[google.cloud.backupdr_v1beta.types.AccessConfig]): + Optional. An array of configurations for this interface. + Currently, only one access config,ONE_TO_ONE_NAT is + supported. If there are no accessConfigs specified, then + this instance will have no external internet access. + ipv6_access_configs (MutableSequence[google.cloud.backupdr_v1beta.types.AccessConfig]): + Optional. An array of IPv6 access configurations for this + interface. Currently, only one IPv6 access config, + DIRECT_IPV6, is supported. If there is no ipv6AccessConfig + specified, then this instance will have no external IPv6 + Internet access. + alias_ip_ranges (MutableSequence[google.cloud.backupdr_v1beta.types.AliasIpRange]): + Optional. An array of alias IP ranges for + this network interface. You can only specify + this field for network interfaces in VPC + networks. + stack_type (google.cloud.backupdr_v1beta.types.NetworkInterface.StackType): + The stack type for this network interface. + + This field is a member of `oneof`_ ``_stack_type``. + ipv6_access_type (google.cloud.backupdr_v1beta.types.NetworkInterface.Ipv6AccessType): + Optional. [Output Only] One of EXTERNAL, INTERNAL to + indicate whether the IP can be accessed from the Internet. + This field is always inherited from its subnetwork. + + This field is a member of `oneof`_ ``_ipv6_access_type``. + queue_count (int): + Optional. The networking queue count that's + specified by users for the network interface. + Both Rx and Tx queues will be set to this + number. It'll be empty if not specified by the + users. + + This field is a member of `oneof`_ ``_queue_count``. + nic_type (google.cloud.backupdr_v1beta.types.NetworkInterface.NicType): + Optional. The type of vNIC to be used on this + interface. This may be gVNIC or VirtioNet. + + This field is a member of `oneof`_ ``_nic_type``. + network_attachment (str): + Optional. The URL of the network attachment that this + interface should connect to in the following format: + projects/{project_number}/regions/{region_name}/networkAttachments/{network_attachment_name}. + + This field is a member of `oneof`_ ``_network_attachment``. + """ + + class StackType(proto.Enum): + r"""Stack type for this network interface. + + Values: + STACK_TYPE_UNSPECIFIED (0): + Default should be STACK_TYPE_UNSPECIFIED. + IPV4_ONLY (1): + The network interface will be assigned IPv4 + address. + IPV4_IPV6 (2): + The network interface can have both IPv4 and + IPv6 addresses. + """ + + STACK_TYPE_UNSPECIFIED = 0 + IPV4_ONLY = 1 + IPV4_IPV6 = 2 + + class Ipv6AccessType(proto.Enum): + r"""IPv6 access type for this network interface. + + Values: + UNSPECIFIED_IPV6_ACCESS_TYPE (0): + IPv6 access type not set. Means this network + interface hasn't been turned on IPv6 yet. + INTERNAL (1): + This network interface can have internal + IPv6. + EXTERNAL (2): + This network interface can have external + IPv6. + """ + + UNSPECIFIED_IPV6_ACCESS_TYPE = 0 + INTERNAL = 1 + EXTERNAL = 2 + + class NicType(proto.Enum): + r"""Nic type for this network interface. + + Values: + NIC_TYPE_UNSPECIFIED (0): + Default should be NIC_TYPE_UNSPECIFIED. + VIRTIO_NET (1): + VIRTIO + GVNIC (2): + GVNIC + """ + + NIC_TYPE_UNSPECIFIED = 0 + VIRTIO_NET = 1 + GVNIC = 2 + + network: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + ip_address: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + ipv6_address: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + internal_ipv6_prefix_length: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + access_configs: MutableSequence["AccessConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="AccessConfig", + ) + ipv6_access_configs: MutableSequence["AccessConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="AccessConfig", + ) + alias_ip_ranges: MutableSequence["AliasIpRange"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="AliasIpRange", + ) + stack_type: StackType = proto.Field( + proto.ENUM, + number=10, + optional=True, + enum=StackType, + ) + ipv6_access_type: Ipv6AccessType = proto.Field( + proto.ENUM, + number=11, + optional=True, + enum=Ipv6AccessType, + ) + queue_count: int = proto.Field( + proto.INT32, + number=12, + optional=True, + ) + nic_type: NicType = proto.Field( + proto.ENUM, + number=13, + optional=True, + enum=NicType, + ) + network_attachment: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + + +class AccessConfig(proto.Message): + r"""An access configuration attached to an instance's network + interface. Only one access config per instance is supported. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.cloud.backupdr_v1beta.types.AccessConfig.AccessType): + Optional. In accessConfigs (IPv4), the default and only + option is ONE_TO_ONE_NAT. In ipv6AccessConfigs, the default + and only option is DIRECT_IPV6. + + This field is a member of `oneof`_ ``_type``. + name (str): + Optional. The name of this access + configuration. + + This field is a member of `oneof`_ ``_name``. + external_ip (str): + Optional. The external IP address of this + access configuration. + + This field is a member of `oneof`_ ``_external_ip``. + external_ipv6 (str): + Optional. The external IPv6 address of this + access configuration. + + This field is a member of `oneof`_ ``_external_ipv6``. + external_ipv6_prefix_length (int): + Optional. The prefix length of the external + IPv6 range. + + This field is a member of `oneof`_ ``_external_ipv6_prefix_length``. + set_public_ptr (bool): + Optional. Specifies whether a public DNS + 'PTR' record should be created to map the + external IP address of the instance to a DNS + domain name. + + This field is a member of `oneof`_ ``_set_public_ptr``. + public_ptr_domain_name (str): + Optional. The DNS domain name for the public + PTR record. + + This field is a member of `oneof`_ ``_public_ptr_domain_name``. + network_tier (google.cloud.backupdr_v1beta.types.AccessConfig.NetworkTier): + Optional. This signifies the networking tier + used for configuring this access + + This field is a member of `oneof`_ ``_network_tier``. + """ + + class AccessType(proto.Enum): + r"""The type of configuration. + + Values: + ACCESS_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + ONE_TO_ONE_NAT (1): + ONE_TO_ONE_NAT + DIRECT_IPV6 (2): + Direct IPv6 access. + """ + + ACCESS_TYPE_UNSPECIFIED = 0 + ONE_TO_ONE_NAT = 1 + DIRECT_IPV6 = 2 + + class NetworkTier(proto.Enum): + r"""Network tier property used by addresses, instances and + forwarding rules. + + Values: + NETWORK_TIER_UNSPECIFIED (0): + Default value. This value is unused. + PREMIUM (1): + High quality, Google-grade network tier, + support for all networking products. + STANDARD (2): + Public internet quality, only limited support + for other networking products. + """ + + NETWORK_TIER_UNSPECIFIED = 0 + PREMIUM = 1 + STANDARD = 2 + + type_: AccessType = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=AccessType, + ) + name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + external_ip: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + external_ipv6: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + external_ipv6_prefix_length: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + set_public_ptr: bool = proto.Field( + proto.BOOL, + number=6, + optional=True, + ) + public_ptr_domain_name: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + network_tier: NetworkTier = proto.Field( + proto.ENUM, + number=8, + optional=True, + enum=NetworkTier, + ) + + +class AliasIpRange(proto.Message): + r"""An alias IP range attached to an instance's network + interface. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ip_cidr_range (str): + Optional. The IP alias ranges to allocate for + this interface. + + This field is a member of `oneof`_ ``_ip_cidr_range``. + subnetwork_range_name (str): + Optional. The name of a subnetwork secondary + IP range from which to allocate an IP alias + range. If not specified, the primary range of + the subnetwork is used. + + This field is a member of `oneof`_ ``_subnetwork_range_name``. + """ + + ip_cidr_range: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + subnetwork_range_name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + +class Scheduling(proto.Message): + r"""Sets the scheduling options for an Instance. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + on_host_maintenance (google.cloud.backupdr_v1beta.types.Scheduling.OnHostMaintenance): + Optional. Defines the maintenance behavior + for this instance. + + This field is a member of `oneof`_ ``_on_host_maintenance``. + automatic_restart (bool): + Optional. Specifies whether the instance + should be automatically restarted if it is + terminated by Compute Engine (not terminated by + a user). + + This field is a member of `oneof`_ ``_automatic_restart``. + preemptible (bool): + Optional. Defines whether the instance is + preemptible. + + This field is a member of `oneof`_ ``_preemptible``. + node_affinities (MutableSequence[google.cloud.backupdr_v1beta.types.Scheduling.NodeAffinity]): + Optional. A set of node affinity and + anti-affinity configurations. Overrides + reservationAffinity. + min_node_cpus (int): + Optional. The minimum number of virtual CPUs + this instance will consume when running on a + sole-tenant node. + + This field is a member of `oneof`_ ``_min_node_cpus``. + provisioning_model (google.cloud.backupdr_v1beta.types.Scheduling.ProvisioningModel): + Optional. Specifies the provisioning model of + the instance. + + This field is a member of `oneof`_ ``_provisioning_model``. + instance_termination_action (google.cloud.backupdr_v1beta.types.Scheduling.InstanceTerminationAction): + Optional. Specifies the termination action + for the instance. + + This field is a member of `oneof`_ ``_instance_termination_action``. + local_ssd_recovery_timeout (google.cloud.backupdr_v1beta.types.SchedulingDuration): + Optional. Specifies the maximum amount of + time a Local Ssd Vm should wait while recovery + of the Local Ssd state is attempted. Its value + should be in between 0 and 168 hours with hour + granularity and the default value being 1 hour. + + This field is a member of `oneof`_ ``_local_ssd_recovery_timeout``. + """ + + class OnHostMaintenance(proto.Enum): + r"""Defines the maintenance behavior for this instance= + + Values: + ON_HOST_MAINTENANCE_UNSPECIFIED (0): + Default value. This value is unused. + TERMINATE (1): + Tells Compute Engine to terminate and + (optionally) restart the instance away from the + maintenance activity. + MIGRATE (1000): + Default, Allows Compute Engine to + automatically migrate instances out of the way + of maintenance events. + """ + + ON_HOST_MAINTENANCE_UNSPECIFIED = 0 + TERMINATE = 1 + MIGRATE = 1000 + + class ProvisioningModel(proto.Enum): + r"""Defines the provisioning model for an instance. + + Values: + PROVISIONING_MODEL_UNSPECIFIED (0): + Default value. This value is not used. + STANDARD (1): + Standard provisioning with user controlled + runtime, no discounts. + SPOT (2): + Heavily discounted, no guaranteed runtime. + """ + + PROVISIONING_MODEL_UNSPECIFIED = 0 + STANDARD = 1 + SPOT = 2 + + class InstanceTerminationAction(proto.Enum): + r"""Defines the supported termination actions for an instance. + + Values: + INSTANCE_TERMINATION_ACTION_UNSPECIFIED (0): + Default value. This value is unused. + DELETE (1): + Delete the VM. + STOP (2): + Stop the VM without storing in-memory + content. default action. + """ + + INSTANCE_TERMINATION_ACTION_UNSPECIFIED = 0 + DELETE = 1 + STOP = 2 + + class NodeAffinity(proto.Message): + r"""Node Affinity: the configuration of desired nodes onto which + this Instance could be scheduled. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + key (str): + Optional. Corresponds to the label key of + Node resource. + + This field is a member of `oneof`_ ``_key``. + operator (google.cloud.backupdr_v1beta.types.Scheduling.NodeAffinity.Operator): + Optional. Defines the operation of node + selection. + + This field is a member of `oneof`_ ``_operator``. + values (MutableSequence[str]): + Optional. Corresponds to the label values of + Node resource. + """ + + class Operator(proto.Enum): + r"""Defines the type of node selections. + + Values: + OPERATOR_UNSPECIFIED (0): + Default value. This value is unused. + IN (1): + Requires Compute Engine to seek for matched + nodes. + NOT_IN (2): + Requires Compute Engine to avoid certain + nodes. + """ + + OPERATOR_UNSPECIFIED = 0 + IN = 1 + NOT_IN = 2 + + key: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + operator: "Scheduling.NodeAffinity.Operator" = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum="Scheduling.NodeAffinity.Operator", + ) + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + on_host_maintenance: OnHostMaintenance = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=OnHostMaintenance, + ) + automatic_restart: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + preemptible: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + node_affinities: MutableSequence[NodeAffinity] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=NodeAffinity, + ) + min_node_cpus: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + provisioning_model: ProvisioningModel = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum=ProvisioningModel, + ) + instance_termination_action: InstanceTerminationAction = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum=InstanceTerminationAction, + ) + local_ssd_recovery_timeout: "SchedulingDuration" = proto.Field( + proto.MESSAGE, + number=10, + optional=True, + message="SchedulingDuration", + ) + + +class SchedulingDuration(proto.Message): + r"""A SchedulingDuration represents a fixed-length span of time + represented as a count of seconds and fractions of seconds at + nanosecond resolution. It is independent of any calendar and + concepts like "day" or "month". Range is approximately 10,000 + years. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + seconds (int): + Optional. Span of time at a resolution of a + second. + + This field is a member of `oneof`_ ``_seconds``. + nanos (int): + Optional. Span of time that's a fraction of a + second at nanosecond resolution. + + This field is a member of `oneof`_ ``_nanos``. + """ + + seconds: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + nanos: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class ServiceAccount(proto.Message): + r"""A service account. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + email (str): + Optional. Email address of the service + account. + + This field is a member of `oneof`_ ``_email``. + scopes (MutableSequence[str]): + Optional. The list of scopes to be made + available for this service account. + """ + + email: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class Tags(proto.Message): + r"""A set of instance tags. + + Attributes: + items (MutableSequence[str]): + Optional. An array of tags. Each tag must be + 1-63 characters long, and comply with RFC1035. + """ + + items: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class AttachedDisk(proto.Message): + r"""An instance-attached disk resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + initialize_params (google.cloud.backupdr_v1beta.types.AttachedDisk.InitializeParams): + Optional. Specifies the parameters to + initialize this disk. + + This field is a member of `oneof`_ ``_initialize_params``. + device_name (str): + Optional. This is used as an identifier for the disks. This + is the unique name has to provided to modify disk parameters + like disk_name and replica_zones (in case of RePDs) + + This field is a member of `oneof`_ ``_device_name``. + kind (str): + Optional. Type of the resource. + + This field is a member of `oneof`_ ``_kind``. + disk_type_deprecated (google.cloud.backupdr_v1beta.types.AttachedDisk.DiskType): + Specifies the type of the disk. + + This field is a member of `oneof`_ ``_disk_type_deprecated``. + mode (google.cloud.backupdr_v1beta.types.AttachedDisk.DiskMode): + Optional. The mode in which to attach this + disk. + + This field is a member of `oneof`_ ``_mode``. + source (str): + Optional. Specifies a valid partial or full + URL to an existing Persistent Disk resource. + + This field is a member of `oneof`_ ``_source``. + index (int): + Optional. A zero-based index to this disk, + where 0 is reserved for the boot disk. + + This field is a member of `oneof`_ ``_index``. + boot (bool): + Optional. Indicates that this is a boot disk. + The virtual machine will use the first partition + of the disk for its root filesystem. + + This field is a member of `oneof`_ ``_boot``. + auto_delete (bool): + Optional. Specifies whether the disk will be + auto-deleted when the instance is deleted (but + not when the disk is detached from the + instance). + + This field is a member of `oneof`_ ``_auto_delete``. + license_ (MutableSequence[str]): + Optional. Any valid publicly visible + licenses. + disk_interface (google.cloud.backupdr_v1beta.types.AttachedDisk.DiskInterface): + Optional. Specifies the disk interface to use + for attaching this disk. + + This field is a member of `oneof`_ ``_disk_interface``. + guest_os_feature (MutableSequence[google.cloud.backupdr_v1beta.types.GuestOsFeature]): + Optional. A list of features to enable on the + guest operating system. Applicable only for + bootable images. + disk_encryption_key (google.cloud.backupdr_v1beta.types.CustomerEncryptionKey): + Optional. Encrypts or decrypts a disk using a + customer-supplied encryption key. + + This field is a member of `oneof`_ ``_disk_encryption_key``. + disk_size_gb (int): + Optional. The size of the disk in GB. + + This field is a member of `oneof`_ ``_disk_size_gb``. + saved_state (google.cloud.backupdr_v1beta.types.AttachedDisk.DiskSavedState): + Optional. Output only. The state of the disk. + + This field is a member of `oneof`_ ``_saved_state``. + disk_type (str): + Optional. Output only. The URI of the disk + type resource. For example: + projects/project/zones/zone/diskTypes/pd-standard + or pd-ssd + + This field is a member of `oneof`_ ``_disk_type``. + type_ (google.cloud.backupdr_v1beta.types.AttachedDisk.DiskType): + Optional. Specifies the type of the disk. + + This field is a member of `oneof`_ ``_type``. + """ + + class DiskType(proto.Enum): + r"""List of the Disk Types. + + Values: + DISK_TYPE_UNSPECIFIED (0): + Default value, which is unused. + SCRATCH (1): + A scratch disk type. + PERSISTENT (2): + A persistent disk type. + """ + + DISK_TYPE_UNSPECIFIED = 0 + SCRATCH = 1 + PERSISTENT = 2 + + class DiskMode(proto.Enum): + r"""List of the Disk Modes. + + Values: + DISK_MODE_UNSPECIFIED (0): + Default value, which is unused. + READ_WRITE (1): + Attaches this disk in read-write mode. Only + one virtual machine at a time can be attached to + a disk in read-write mode. + READ_ONLY (2): + Attaches this disk in read-only mode. + Multiple virtual machines can use a disk in + read-only mode at a time. + LOCKED (3): + The disk is locked for administrative + reasons. Nobody else can use the disk. This mode + is used (for example) when taking a snapshot of + a disk to prevent mounting the disk while it is + being snapshotted. + """ + + DISK_MODE_UNSPECIFIED = 0 + READ_WRITE = 1 + READ_ONLY = 2 + LOCKED = 3 + + class DiskInterface(proto.Enum): + r"""List of the Disk Interfaces. + + Values: + DISK_INTERFACE_UNSPECIFIED (0): + Default value, which is unused. + SCSI (1): + SCSI Disk Interface. + NVME (2): + NVME Disk Interface. + NVDIMM (3): + NVDIMM Disk Interface. + ISCSI (4): + ISCSI Disk Interface. + """ + + DISK_INTERFACE_UNSPECIFIED = 0 + SCSI = 1 + NVME = 2 + NVDIMM = 3 + ISCSI = 4 + + class DiskSavedState(proto.Enum): + r"""List of the states of the Disk. + + Values: + DISK_SAVED_STATE_UNSPECIFIED (0): + Default Disk state has not been preserved. + PRESERVED (1): + Disk state has been preserved. + """ + + DISK_SAVED_STATE_UNSPECIFIED = 0 + PRESERVED = 1 + + class InitializeParams(proto.Message): + r"""Specifies the parameters to initialize this disk. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disk_name (str): + Optional. Specifies the disk name. If not + specified, the default is to use the name of the + instance. + + This field is a member of `oneof`_ ``_disk_name``. + replica_zones (MutableSequence[str]): + Optional. URL of the zone where the disk + should be created. Required for each regional + disk associated with the instance. + """ + + disk_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + replica_zones: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + initialize_params: InitializeParams = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message=InitializeParams, + ) + device_name: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + disk_type_deprecated: DiskType = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum=DiskType, + ) + mode: DiskMode = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum=DiskMode, + ) + source: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + index: int = proto.Field( + proto.INT64, + number=9, + optional=True, + ) + boot: bool = proto.Field( + proto.BOOL, + number=10, + optional=True, + ) + auto_delete: bool = proto.Field( + proto.BOOL, + number=11, + optional=True, + ) + license_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + disk_interface: DiskInterface = proto.Field( + proto.ENUM, + number=13, + optional=True, + enum=DiskInterface, + ) + guest_os_feature: MutableSequence["GuestOsFeature"] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message="GuestOsFeature", + ) + disk_encryption_key: "CustomerEncryptionKey" = proto.Field( + proto.MESSAGE, + number=15, + optional=True, + message="CustomerEncryptionKey", + ) + disk_size_gb: int = proto.Field( + proto.INT64, + number=16, + optional=True, + ) + saved_state: DiskSavedState = proto.Field( + proto.ENUM, + number=17, + optional=True, + enum=DiskSavedState, + ) + disk_type: str = proto.Field( + proto.STRING, + number=18, + optional=True, + ) + type_: DiskType = proto.Field( + proto.ENUM, + number=19, + optional=True, + enum=DiskType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/bindingmatchingresource.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/bindingmatchingresource.py new file mode 100644 index 000000000000..6b5e6b15f218 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/bindingmatchingresource.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "GetBindingMatchingResourceRequest", + "ListBindingMatchingResourcesRequest", + "ListBindingMatchingResourcesResponse", + "BindingMatchingResource", + "AutoProtectionDetails", + }, +) + + +class GetBindingMatchingResourceRequest(proto.Message): + r"""Request message for getting a BindingMatchingResource. + + Attributes: + name (str): + Required. The name of the matching resource to retrieve. + Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBindingMatchingResourcesRequest(proto.Message): + r"""Request message for List BindingMatchingResources. + + Attributes: + parent (str): + Required. The project, location, auto protection policy and + binding for which to retrieve ``BindingMatchingResources`` + information. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}``. + In Google Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. + page_size (int): + Optional. The maximum number of ``BindingMatchingResources`` + to return in a single response. The default page size is 100 + and maximum page size is 200. Note that the response may + include a partial list and a caller should only rely on the + response's + [next_page_token][google.cloud.backupdr.v1beta.ListBindingMatchingResourcesResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + Optional. The value of + [next_page_token][google.cloud.backupdr.v1beta.ListBindingMatchingResourcesResponse.next_page_token] + received from a previous ``ListBindingMatchingResources`` + call. Provide this to retrieve the subsequent page in a + multi-page list of results. When paginating, all other + parameters provided to ``ListBindingMatchingResources`` must + match the call that provided the page token. + filter (str): + Optional. Field match expression used to + filter the results. + order_by (str): + Optional. Field by which to sort the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListBindingMatchingResourcesResponse(proto.Message): + r"""The response message for getting a list of + ``BindingMatchingResources``. + + Attributes: + matching_resources (MutableSequence[google.cloud.backupdr_v1beta.types.BindingMatchingResource]): + The list of ``BindingMatchingResources`` in the + project,location for the specified binding. + next_page_token (str): + A token which may be sent as + [page_token][google.cloud.backupdr.v1beta.ListBindingMatchingResourcesRequest.page_token] + in a subsequent ``ListBindingMatchingResources`` call to + retrieve the next page of results. If this field is omitted + or empty, then there are no more results to return. + """ + + @property + def raw_page(self): + return self + + matching_resources: MutableSequence["BindingMatchingResource"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BindingMatchingResource", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BindingMatchingResource(proto.Message): + r"""BindingMatchingResource contains the details of a resource + that matches the criteria of a binding. + + Attributes: + name (str): + Identifier. The resource name of the + ``BindingMatchingResource``. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource}`` + resource (str): + Required. Immutable. Resource name of the workload that + matches the criteria of the binding. + + The format can be either a relative resource name (e.g., + ``projects/my-project/zones/us-central1-a/instances/my-instance``) + or a schemeless full resource name (e.g., + ``//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance``). + last_evaluation_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was last evaluated for protection. + auto_protection_details (google.cloud.backupdr_v1beta.types.AutoProtectionDetails): + Output only. The auto protection details of + the resource from the current binding's + perspective. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: str = proto.Field( + proto.STRING, + number=2, + ) + last_evaluation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + auto_protection_details: "AutoProtectionDetails" = proto.Field( + proto.MESSAGE, + number=4, + message="AutoProtectionDetails", + ) + + +class AutoProtectionDetails(proto.Message): + r"""AutoProtectionDetails contains the protection details of a + resource from the current binding's perspective. + + Attributes: + state (google.cloud.backupdr_v1beta.types.AutoProtectionDetails.State): + Output only. Protection state of the resource + from the current binding's perspective. Output + only. + backup_plan_association (str): + Output only. Resource name of backup plan + association linked to the resource, if any. + Format: + + projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId} + data_source (str): + Output only. Resource name of the datasource + linked to the resource, if any. Format: + + projects/{project}/locations/{location}/backupVaults/{backupVaultId}/dataSources/{dataSourceId} + error (google.rpc.status_pb2.Status): + Output only. Error during last sync for + protection/unprotection, if any. + """ + + class State(proto.Enum): + r"""Enum for protection state of the resource. + + Values: + STATE_UNSPECIFIED (0): + State unspecified. + PROTECTED (1): + Resource is protected. + PROTECTION_FAILED (2): + Resource protection failed. + UNPROTECTING (3): + Resource is being unprotected. + UNPROTECTION_FAILED (4): + Resource unprotection failed. + """ + + STATE_UNSPECIFIED = 0 + PROTECTED = 1 + PROTECTION_FAILED = 2 + UNPROTECTING = 3 + UNPROTECTION_FAILED = 4 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + backup_plan_association: str = proto.Field( + proto.STRING, + number=2, + ) + data_source: str = proto.Field( + proto.STRING, + number=3, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/datasourcereference.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/datasourcereference.py new file mode 100644 index 000000000000..8c0515e97c1d --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/datasourcereference.py @@ -0,0 +1,432 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1beta.types import ( + backupvault, + backupvault_alloydb, + backupvault_cloudsql, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "DataSourceReference", + "DataSourceBackupConfigInfo", + "DataSourceGcpResourceInfo", + "GetDataSourceReferenceRequest", + "ListDataSourceReferencesRequest", + "ListDataSourceReferencesResponse", + "FetchDataSourceReferencesForResourceTypeRequest", + "FetchDataSourceReferencesForResourceTypeResponse", + }, +) + + +class DataSourceReference(proto.Message): + r"""DataSourceReference is a reference to a DataSource resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the DataSourceReference. + Format: + projects/{project}/locations/{location}/dataSourceReferences/{data_source_reference} + data_source (str): + Output only. The resource name of the + DataSource. Format: + + projects/{project}/locations/{location}/backupVaults/{backupVault}/dataSources/{dataSource} + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the + DataSourceReference was created. + data_source_backup_config_state (google.cloud.backupdr_v1beta.types.BackupConfigState): + Output only. The backup configuration state + of the DataSource. + data_source_backup_count (int): + Output only. Number of backups in the + DataSource. + data_source_backup_config_info (google.cloud.backupdr_v1beta.types.DataSourceBackupConfigInfo): + Output only. Information of backup + configuration on the DataSource. + data_source_gcp_resource_info (google.cloud.backupdr_v1beta.types.DataSourceGcpResourceInfo): + Output only. The Google Cloud resource that + the DataSource is associated with. + total_stored_bytes (int): + Output only. Total size of the storage used + by all backup resources for the referenced + datasource. + + This field is a member of `oneof`_ ``_total_stored_bytes``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data_source: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + data_source_backup_config_state: backupvault.BackupConfigState = proto.Field( + proto.ENUM, + number=4, + enum=backupvault.BackupConfigState, + ) + data_source_backup_count: int = proto.Field( + proto.INT64, + number=5, + ) + data_source_backup_config_info: "DataSourceBackupConfigInfo" = proto.Field( + proto.MESSAGE, + number=6, + message="DataSourceBackupConfigInfo", + ) + data_source_gcp_resource_info: "DataSourceGcpResourceInfo" = proto.Field( + proto.MESSAGE, + number=7, + message="DataSourceGcpResourceInfo", + ) + total_stored_bytes: int = proto.Field( + proto.INT64, + number=8, + optional=True, + ) + + +class DataSourceBackupConfigInfo(proto.Message): + r"""Information of backup configuration on the DataSource. + + Attributes: + last_backup_state (google.cloud.backupdr_v1beta.types.BackupConfigInfo.LastBackupState): + Output only. The status of the last backup in + this DataSource + last_successful_backup_consistency_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp of the last successful + backup to this DataSource. + """ + + last_backup_state: backupvault.BackupConfigInfo.LastBackupState = proto.Field( + proto.ENUM, + number=1, + enum=backupvault.BackupConfigInfo.LastBackupState, + ) + last_successful_backup_consistency_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DataSourceGcpResourceInfo(proto.Message): + r"""The Google Cloud resource that the DataSource is associated + with. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_sql_instance_properties (google.cloud.backupdr_v1beta.types.CloudSqlInstanceDataSourceReferenceProperties): + Output only. The properties of the Cloud SQL + instance. + + This field is a member of `oneof`_ ``resource_properties``. + alloy_db_cluster_properties (google.cloud.backupdr_v1beta.types.AlloyDBClusterDataSourceReferenceProperties): + Output only. The properties of the AlloyDB + cluster. + + This field is a member of `oneof`_ ``resource_properties``. + gcp_resourcename (str): + Output only. The resource name of the Google + Cloud resource. Ex: + projects/{project}/zones/{zone}/instances/{instance} + type_ (str): + Output only. The type of the Google Cloud + resource. Ex: compute.googleapis.com/Instance + location (str): + Output only. The location of the Google Cloud + resource. Ex: + //"global"/"unspecified". + """ + + cloud_sql_instance_properties: backupvault_cloudsql.CloudSqlInstanceDataSourceReferenceProperties = proto.Field( + proto.MESSAGE, + number=4, + oneof="resource_properties", + message=backupvault_cloudsql.CloudSqlInstanceDataSourceReferenceProperties, + ) + alloy_db_cluster_properties: backupvault_alloydb.AlloyDBClusterDataSourceReferenceProperties = proto.Field( + proto.MESSAGE, + number=6, + oneof="resource_properties", + message=backupvault_alloydb.AlloyDBClusterDataSourceReferenceProperties, + ) + gcp_resourcename: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + location: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetDataSourceReferenceRequest(proto.Message): + r"""Request for the GetDataSourceReference method. + + Attributes: + name (str): + Required. The name of the DataSourceReference to retrieve. + Format: + projects/{project}/locations/{location}/dataSourceReferences/{data_source_reference} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDataSourceReferencesRequest(proto.Message): + r"""Request for the ListDataSourceReferences method. + + Attributes: + parent (str): + Required. The parent resource name. + Format: projects/{project}/locations/{location} + page_size (int): + Optional. The maximum number of + DataSourceReferences to return. The service may + return fewer than this value. If unspecified, at + most 50 DataSourceReferences will be returned. + The maximum value is 100; values above 100 will + be coerced to 100. + page_token (str): + Optional. A page token, received from a previous + ``ListDataSourceReferences`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListDataSourceReferences`` must match the call that + provided the page token. + filter (str): + Optional. A filter expression that filters the results + listed in the response. The expression must specify the + field name, a comparison operator, and the value that you + want to use for filtering. + + The following field and operator combinations are supported: + + - data_source_gcp_resource_info.gcp_resourcename with ``=``, + ``!=`` + - data_source_gcp_resource_info.type with ``=``, ``!=`` + order_by (str): + Optional. A comma-separated list of fields to order by, + sorted in ascending order. Use "desc" after a field name for + descending. + + Supported fields: + + - data_source + - data_source_gcp_resource_info.gcp_resourcename + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListDataSourceReferencesResponse(proto.Message): + r"""Response for the ListDataSourceReferences method. + + Attributes: + data_source_references (MutableSequence[google.cloud.backupdr_v1beta.types.DataSourceReference]): + The DataSourceReferences from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + data_source_references: MutableSequence["DataSourceReference"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="DataSourceReference", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class FetchDataSourceReferencesForResourceTypeRequest(proto.Message): + r"""Request for the FetchDataSourceReferencesForResourceType + method. + + Attributes: + parent (str): + Required. The parent resource name. + Format: projects/{project}/locations/{location} + resource_type (str): + Required. The type of the Google Cloud + resource. Ex: sql.googleapis.com/Instance + page_size (int): + Optional. The maximum number of + DataSourceReferences to return. The service may + return fewer than this value. If unspecified, at + most 50 DataSourceReferences will be returned. + The maximum value is 100; values above 100 will + be coerced to 100. + page_token (str): + Optional. A page token, received from a previous call of + ``FetchDataSourceReferencesForResourceType``. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``FetchDataSourceReferencesForResourceType`` must match the + call that provided the page token. + filter (str): + Optional. A filter expression that filters the results + fetched in the response. The expression must specify the + field name, a comparison operator, and the value that you + want to use for filtering. Supported fields: + + - data_source + - data_source_gcp_resource_info.gcp_resourcename + - data_source_backup_config_state + - data_source_backup_count + - data_source_backup_config_info.last_backup_state + - data_source_gcp_resource_info.gcp_resourcename + - data_source_gcp_resource_info.type + - data_source_gcp_resource_info.location + - data_source_gcp_resource_info.cloud_sql_instance_properties.instance_create_time + order_by (str): + Optional. A comma-separated list of fields to order by, + sorted in ascending order. Use "desc" after a field name for + descending. + + Supported fields: + + - name + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + + +class FetchDataSourceReferencesForResourceTypeResponse(proto.Message): + r"""Response for the FetchDataSourceReferencesForResourceType + method. + + Attributes: + data_source_references (MutableSequence[google.cloud.backupdr_v1beta.types.DataSourceReference]): + The DataSourceReferences from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + data_source_references: MutableSequence["DataSourceReference"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="DataSourceReference", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/protection_summary.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/protection_summary.py new file mode 100644 index 000000000000..03c0ddf02dc4 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/protection_summary.py @@ -0,0 +1,517 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "ListResourceBackupConfigsRequest", + "ListResourceBackupConfigsResponse", + "ResourceBackupConfig", + "BackupConfigDetails", + "PitrSettings", + "BackupDrTemplateConfig", + "BackupDrPlanConfig", + "BackupDrPlanRule", + "BackupLocation", + }, +) + + +class ListResourceBackupConfigsRequest(proto.Message): + r"""Request for ListResourceBackupConfigs. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + resource backup configs. Format: + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud regions, + for example **us-central1**. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will use 100 as default. + Maximum value is 500 and values above 500 will + be coerced to 500. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListResourceBackupConfigsResponse(proto.Message): + r"""Response for ListResourceBackupConfigs. + + Attributes: + resource_backup_configs (MutableSequence[google.cloud.backupdr_v1beta.types.ResourceBackupConfig]): + The list of ResourceBackupConfigs for the + specified scope. + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + resource_backup_configs: MutableSequence["ResourceBackupConfig"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ResourceBackupConfig", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ResourceBackupConfig(proto.Message): + r"""ResourceBackupConfig represents a resource along with its + backup configurations. + + Attributes: + name (str): + Identifier. The resource name of the + ResourceBackupConfig. Format: + + projects/{project}/locations/{location}/resourceBackupConfigs/{uid} + uid (str): + Output only. The unique identifier of the + resource backup config. + target_resource (str): + Output only. The `full resource + name `__ + of the cloud resource that this configuration applies to. + Supported resource types are + [ResourceBackupConfig.ResourceType][google.cloud.backupdr.v1beta.ResourceBackupConfig.ResourceType]. + target_resource_display_name (str): + Output only. The human friendly name of the + target resource. + target_resource_type (google.cloud.backupdr_v1beta.types.ResourceBackupConfig.ResourceType): + Output only. The type of the target resource. + target_resource_labels (MutableMapping[str, str]): + Labels associated with the target resource. + backup_configs_details (MutableSequence[google.cloud.backupdr_v1beta.types.BackupConfigDetails]): + Backup configurations applying to the target + resource, including those targeting its + related/child resources. For example, backup + configuration applicable to Compute Engine disks + will be populated in this field for a Compute + Engine VM which has the disk associated. + backup_configured (bool): + Output only. Whether the target resource is configured for + backup. This is true if the backup_configs_details is not + empty. + vaulted (bool): + Output only. Whether the target resource is protected by a + backup vault. This is true if the backup_configs_details is + not empty and any of the + [ResourceBackupConfig.backup_configs_details][google.cloud.backupdr.v1beta.ResourceBackupConfig.backup_configs_details] + has a backup configuration with + [BackupConfigDetails.backup_vault][google.cloud.backupdr.v1beta.BackupConfigDetails.backup_vault] + set. + """ + + class ResourceType(proto.Enum): + r"""The type of the cloud resource. + + Values: + RESOURCE_TYPE_UNSPECIFIED (0): + Resource type not set. + CLOUD_SQL_INSTANCE (1): + Cloud SQL instance. + COMPUTE_ENGINE_VM (2): + Compute Engine VM. + COMPUTE_ENGINE_DISK (3): + Compute Engine Disk. + COMPUTE_ENGINE_REGIONAL_DISK (4): + Compute Engine Regional Disk. + """ + + RESOURCE_TYPE_UNSPECIFIED = 0 + CLOUD_SQL_INSTANCE = 1 + COMPUTE_ENGINE_VM = 2 + COMPUTE_ENGINE_DISK = 3 + COMPUTE_ENGINE_REGIONAL_DISK = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + target_resource: str = proto.Field( + proto.STRING, + number=3, + ) + target_resource_display_name: str = proto.Field( + proto.STRING, + number=4, + ) + target_resource_type: ResourceType = proto.Field( + proto.ENUM, + number=5, + enum=ResourceType, + ) + target_resource_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + backup_configs_details: MutableSequence["BackupConfigDetails"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=7, + message="BackupConfigDetails", + ) + ) + backup_configured: bool = proto.Field( + proto.BOOL, + number=8, + ) + vaulted: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +class BackupConfigDetails(proto.Message): + r"""BackupConfigDetails has information about how the resource is + configured for backups and about the most recent backup taken + for this configuration. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + backup_dr_plan_config (google.cloud.backupdr_v1beta.types.BackupDrPlanConfig): + Google Cloud Backup and DR's Backup Plan + specific data. + + This field is a member of `oneof`_ ``plan_specific_config``. + backup_dr_template_config (google.cloud.backupdr_v1beta.types.BackupDrTemplateConfig): + Google Cloud Backup and DR's Template + specific data. + + This field is a member of `oneof`_ ``plan_specific_config``. + backup_config_source (str): + Output only. The full resource name of the + backup config source resource. For example, + "//backupdr.googleapis.com/v1/projects/{project}/locations/{region}/backupPlans/{backupplanId}" + or + "//compute.googleapis.com/projects/{project}/locations/{region}/resourcePolicies/{resourcePolicyId}". + backup_config_source_display_name (str): + Output only. The display name of the backup + config source resource. + type_ (google.cloud.backupdr_v1beta.types.BackupConfigDetails.Type): + Output only. The type of the backup config + resource. + state (google.cloud.backupdr_v1beta.types.BackupConfigDetails.State): + Output only. The state of the backup config + resource. + pitr_settings (google.cloud.backupdr_v1beta.types.PitrSettings): + Output only. Point in time recovery settings + of the backup configuration resource. + latest_successful_backup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp of the latest + successful backup created via this backup + configuration. + applicable_resource (str): + Output only. The `full resource + name `__ + of the resource that is applicable for the backup + configuration. Example: + "//compute.googleapis.com/projects/{project}/zones/{zone}/instances/{instance}". + backup_vault (str): + Output only. The `full resource + name `__ + of the backup vault that will store the backups generated + through this backup configuration. Example: + "//backupdr.googleapis.com/v1/projects/{project}/locations/{region}/backupVaults/{backupvaultId}". + backup_locations (MutableSequence[google.cloud.backupdr_v1beta.types.BackupLocation]): + The locations where the backups are to be + stored. + """ + + class Type(proto.Enum): + r"""Type of the backup configuration. + This enum may receive new values in the future. + + Values: + TYPE_UNSPECIFIED (0): + Backup config type is unspecified. + CLOUD_SQL_INSTANCE_BACKUP_CONFIG (1): + Backup config is Cloud SQL instance's + automated backup config. + COMPUTE_ENGINE_RESOURCE_POLICY (2): + Backup config is Compute Engine Resource + Policy. + BACKUPDR_BACKUP_PLAN (3): + Backup config is Google Cloud Backup and DR's + Backup Plan. + BACKUPDR_TEMPLATE (4): + Backup config is Google Cloud Backup and DR's + Template. + """ + + TYPE_UNSPECIFIED = 0 + CLOUD_SQL_INSTANCE_BACKUP_CONFIG = 1 + COMPUTE_ENGINE_RESOURCE_POLICY = 2 + BACKUPDR_BACKUP_PLAN = 3 + BACKUPDR_TEMPLATE = 4 + + class State(proto.Enum): + r"""The state tells whether the backup config is active or not. + + Values: + STATE_UNSPECIFIED (0): + Backup config state not set. + ACTIVE (1): + The config is in an active state protecting + the resource + INACTIVE (2): + The config is currently not protecting the + resource. Either because it is disabled or the + owning project has been deleted without cleanup + of the actual resource. + ERROR (3): + The config still exists but because of some + error state it is not protecting the resource. + Like the source project is deleted. For eg. + PlanAssociation, BackupPlan is deleted. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + ERROR = 3 + + backup_dr_plan_config: "BackupDrPlanConfig" = proto.Field( + proto.MESSAGE, + number=10, + oneof="plan_specific_config", + message="BackupDrPlanConfig", + ) + backup_dr_template_config: "BackupDrTemplateConfig" = proto.Field( + proto.MESSAGE, + number=11, + oneof="plan_specific_config", + message="BackupDrTemplateConfig", + ) + backup_config_source: str = proto.Field( + proto.STRING, + number=1, + ) + backup_config_source_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: Type = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + pitr_settings: "PitrSettings" = proto.Field( + proto.MESSAGE, + number=5, + message="PitrSettings", + ) + latest_successful_backup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + applicable_resource: str = proto.Field( + proto.STRING, + number=7, + ) + backup_vault: str = proto.Field( + proto.STRING, + number=8, + ) + backup_locations: MutableSequence["BackupLocation"] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message="BackupLocation", + ) + + +class PitrSettings(proto.Message): + r"""Point in time recovery settings of the backup configuration + resource. + + Attributes: + retention_days (int): + Output only. Number of days to retain the + backup. + """ + + retention_days: int = proto.Field( + proto.INT32, + number=1, + ) + + +class BackupDrTemplateConfig(proto.Message): + r"""Provides additional information about Google Cloud Backup and + DR's Template backup configuration. + + Attributes: + first_party_management_uri (str): + Output only. The URI of the BackupDr template + resource for the first party identity users. + third_party_management_uri (str): + Output only. The URI of the BackupDr template + resource for the third party identity users. + """ + + first_party_management_uri: str = proto.Field( + proto.STRING, + number=1, + ) + third_party_management_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BackupDrPlanConfig(proto.Message): + r"""BackupDrPlanConfig has additional information about Google + Cloud Backup and DR's Plan backup configuration. + + Attributes: + backup_dr_plan_rules (MutableSequence[google.cloud.backupdr_v1beta.types.BackupDrPlanRule]): + Backup rules of the backup plan resource. + """ + + backup_dr_plan_rules: MutableSequence["BackupDrPlanRule"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupDrPlanRule", + ) + + +class BackupDrPlanRule(proto.Message): + r"""BackupDrPlanRule has rule specific information of the backup + plan resource. + + Attributes: + rule_id (str): + Output only. Unique Id of the backup rule. + last_successful_backup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp of the latest + successful backup created via this backup rule. + """ + + rule_id: str = proto.Field( + proto.STRING, + number=1, + ) + last_successful_backup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class BackupLocation(proto.Message): + r"""BackupLocation represents a cloud location where a backup can + be stored. + + Attributes: + type_ (google.cloud.backupdr_v1beta.types.BackupLocation.Type): + Output only. The type of the location. + location_id (str): + Output only. The id of the cloud location. + Example: "us-central1". + """ + + class Type(proto.Enum): + r"""The type of the location. + + Values: + TYPE_UNSPECIFIED (0): + Location type is unspecified. + ZONAL (1): + Location type is zonal. + REGIONAL (2): + Location type is regional. + MULTI_REGIONAL (3): + Location type is multi regional. + """ + + TYPE_UNSPECIFIED = 0 + ZONAL = 1 + REGIONAL = 2 + MULTI_REGIONAL = 3 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + location_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_async.py new file mode 100644 index 000000000000..4fe457957d39 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_async.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1beta.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_async.py new file mode 100644 index 000000000000..1ea83a42752e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAutoProtectionPolicyBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicyBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1beta.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1beta.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = await client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicyBinding_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_sync.py new file mode 100644 index 000000000000..b9361cf2bfe8 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAutoProtectionPolicyBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicyBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1beta.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1beta.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicyBinding_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_sync.py new file mode 100644 index 000000000000..881ed43696e3 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_sync.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1beta.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_association_async.py new file mode 100644 index 000000000000..13002b935ca0 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_association_async.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateBackupPlanAssociation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_create_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = await client.create_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateBackupPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_association_sync.py new file mode 100644 index 000000000000..d84b21eab20c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_association_sync.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateBackupPlanAssociation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_create_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = client.create_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateBackupPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_async.py new file mode 100644 index 000000000000..646347abfd6b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateBackupPlan_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_create_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.CreateBackupPlanRequest( + parent="parent_value", + backup_plan_id="backup_plan_id_value", + backup_plan=backup_plan, + ) + + # Make the request + operation = await client.create_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateBackupPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_sync.py new file mode 100644 index 000000000000..22c8f446db75 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_plan_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateBackupPlan_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_create_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.CreateBackupPlanRequest( + parent="parent_value", + backup_plan_id="backup_plan_id_value", + backup_plan=backup_plan, + ) + + # Make the request + operation = client.create_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateBackupPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_vault_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_vault_async.py new file mode 100644 index 000000000000..8189b6e76f1d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_vault_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateBackupVault_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_create_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) + + # Make the request + operation = await client.create_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateBackupVault_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_vault_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_vault_sync.py new file mode 100644 index 000000000000..d0a535a12b33 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_backup_vault_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateBackupVault_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_create_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) + + # Make the request + operation = client.create_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateBackupVault_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_management_server_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_management_server_async.py new file mode 100644 index 000000000000..4795eb72c513 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_management_server_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateManagementServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateManagementServer_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_create_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + ) + + # Make the request + operation = await client.create_management_server(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateManagementServer_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_management_server_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_management_server_sync.py new file mode 100644 index 000000000000..af1e5a485c24 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_management_server_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateManagementServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateManagementServer_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_create_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + ) + + # Make the request + operation = client.create_management_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateManagementServer_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py new file mode 100644 index 000000000000..387b93b90ecc --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py new file mode 100644 index 000000000000..9c3ed459276f --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_async.py new file mode 100644 index 000000000000..01189b51363d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_delete_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackup_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py new file mode 100644 index 000000000000..d2054f5d10bb --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_delete_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py new file mode 100644 index 000000000000..179c9d199475 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_delete_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py new file mode 100644 index 000000000000..f55b9f2723f7 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_delete_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py new file mode 100644 index 000000000000..cf6e10fcf2b1 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_delete_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupPlanRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_sync.py new file mode 100644 index 000000000000..7a1b6d038f20 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_delete_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackup_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py new file mode 100644 index 000000000000..8e9f1a9ae132 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackupVault_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_delete_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupVaultRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackupVault_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py new file mode 100644 index 000000000000..0dda4eed9578 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteBackupVault_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_delete_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteBackupVaultRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteBackupVault_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_management_server_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_management_server_async.py new file mode 100644 index 000000000000..7e7767ecae5a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_management_server_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteManagementServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteManagementServer_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_delete_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteManagementServerRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_management_server(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteManagementServer_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py new file mode 100644 index 000000000000..83a8a93b5b58 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteManagementServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteManagementServer_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_delete_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteManagementServerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_management_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteManagementServer_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py new file mode 100644 index 000000000000..76e38450bb50 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchBackupPlanAssociationsForResourceType +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_fetch_backup_plan_associations_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backup_plan_associations_for_resource_type( + request=request + ) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py new file mode 100644 index 000000000000..fd5657180b2e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchBackupPlanAssociationsForResourceType +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_fetch_backup_plan_associations_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backup_plan_associations_for_resource_type( + request=request + ) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py new file mode 100644 index 000000000000..1e0a5ab93a86 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchBackupsForResourceType +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_fetch_backups_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backups_for_resource_type(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py new file mode 100644 index 000000000000..865c8ba4589a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchBackupsForResourceType +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_fetch_backups_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchBackupsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_backups_for_resource_type(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py new file mode 100644 index 000000000000..937cc745d114 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchDataSourceReferencesForResourceType +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_fetch_data_source_references_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_data_source_references_for_resource_type(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py new file mode 100644 index 000000000000..a29f256b7cb9 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchDataSourceReferencesForResourceType +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_fetch_data_source_references_for_resource_type(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Make the request + page_result = client.fetch_data_source_references_for_resource_type(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py new file mode 100644 index 000000000000..69ac7ca27d20 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchUsableBackupVaults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_fetch_usable_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchUsableBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.fetch_usable_backup_vaults(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py new file mode 100644 index 000000000000..14aea1df3aff --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchUsableBackupVaults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_fetch_usable_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.FetchUsableBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.fetch_usable_backup_vaults(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py new file mode 100644 index 000000000000..c1a40d8ae12b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py new file mode 100644 index 000000000000..57d90b7c3e7a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutoProtectionPolicyBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py new file mode 100644 index 000000000000..2c895330ac73 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutoProtectionPolicyBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py new file mode 100644 index 000000000000..57478bc537f4 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_async.py new file mode 100644 index 000000000000..0ff2721c1d8b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackup_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py new file mode 100644 index 000000000000..216963cf502b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_plan_association(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py new file mode 100644 index 000000000000..90c9c5440614 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_plan_association(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py new file mode 100644 index 000000000000..272a9a34c99b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupPlan_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_plan(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py new file mode 100644 index 000000000000..cc25eb834a5d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupPlanRevision +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_backup_plan_revision(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_plan_revision(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py new file mode 100644 index 000000000000..bb98b281368b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupPlanRevision +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_backup_plan_revision(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_plan_revision(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py new file mode 100644 index 000000000000..7dc388dcdbe4 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupPlan_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupPlanRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_plan(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_sync.py new file mode 100644 index 000000000000..15dbcb3c0295 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackup_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py new file mode 100644 index 000000000000..80083793e40c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupVault_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupVaultRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_vault(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupVault_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py new file mode 100644 index 000000000000..28537ba73db1 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBackupVault_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBackupVaultRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_vault(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBackupVault_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py new file mode 100644 index 000000000000..22c0ecce00bb --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBindingMatchingResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_binding_matching_resource(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBindingMatchingResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_binding_matching_resource(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py new file mode 100644 index 000000000000..9f702abe9a3e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBindingMatchingResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_binding_matching_resource(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetBindingMatchingResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_binding_matching_resource(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_async.py new file mode 100644 index 000000000000..42158269a2cc --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetDataSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_source(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetDataSource_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py new file mode 100644 index 000000000000..80d97f8d6a30 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSourceReference +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetDataSourceReference_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_data_source_reference(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceReferenceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_source_reference(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetDataSourceReference_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py new file mode 100644 index 000000000000..b1c97dfd7ec3 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSourceReference +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetDataSourceReference_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_data_source_reference(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceReferenceRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_source_reference(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetDataSourceReference_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_sync.py new file mode 100644 index 000000000000..ef38b2ca3fd4 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_data_source_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetDataSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetDataSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_source(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetDataSource_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_management_server_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_management_server_async.py new file mode 100644 index 000000000000..e21e42590722 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_management_server_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetManagementServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetManagementServer_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_get_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetManagementServerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_management_server(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetManagementServer_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_management_server_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_management_server_sync.py new file mode 100644 index 000000000000..9c4ae84d6fd6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_management_server_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetManagementServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetManagementServer_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_get_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetManagementServerRequest( + name="name_value", + ) + + # Make the request + response = client.get_management_server(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetManagementServer_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initialize_service_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initialize_service_async.py new file mode 100644 index 000000000000..f40aa76c1ebb --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initialize_service_async.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InitializeService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_InitializeService_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_initialize_service(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + cloud_sql_instance_initialization_config = ( + backupdr_v1beta.CloudSqlInstanceInitializationConfig() + ) + cloud_sql_instance_initialization_config.edition = "ENTERPRISE_PLUS" + + request = backupdr_v1beta.InitializeServiceRequest( + cloud_sql_instance_initialization_config=cloud_sql_instance_initialization_config, + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = await client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_InitializeService_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initialize_service_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initialize_service_sync.py new file mode 100644 index 000000000000..01735916329d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initialize_service_sync.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InitializeService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_InitializeService_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_initialize_service(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + cloud_sql_instance_initialization_config = ( + backupdr_v1beta.CloudSqlInstanceInitializationConfig() + ) + cloud_sql_instance_initialization_config.edition = "ENTERPRISE_PLUS" + + request = backupdr_v1beta.InitializeServiceRequest( + cloud_sql_instance_initialization_config=cloud_sql_instance_initialization_config, + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_InitializeService_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py new file mode 100644 index 000000000000..a46819c33fff --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InitiateDeleteAutoProtectionPolicyBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = await client.initiate_delete_auto_protection_policy_binding( + request=request + ) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py new file mode 100644 index 000000000000..c7e7e7b40e0f --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for InitiateDeleteAutoProtectionPolicyBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.initiate_delete_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py new file mode 100644 index 000000000000..8c048c8b0257 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAppliedAutoProtectionPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py new file mode 100644 index 000000000000..4ee1d1352211 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAppliedAutoProtectionPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py new file mode 100644 index 000000000000..f2cfc654296b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAutoProtectionPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py new file mode 100644 index 000000000000..0103bfa69d98 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAutoProtectionPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py new file mode 100644 index 000000000000..293eb1d3a532 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAutoProtectionPolicyBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py new file mode 100644 index 000000000000..586a64d79a14 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAutoProtectionPolicyBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py new file mode 100644 index 000000000000..4691215af422 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupPlanAssociations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_backup_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_associations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py new file mode 100644 index 000000000000..844d3aa2831f --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupPlanAssociations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_backup_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_associations(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py new file mode 100644 index 000000000000..0751d87560c8 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupPlanRevisions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_backup_plan_revisions(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py new file mode 100644 index 000000000000..82f9031316c2 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupPlanRevisions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_backup_plan_revisions(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlanRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plan_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py new file mode 100644 index 000000000000..304c06cd8ada --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupPlans +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupPlans_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_backup_plans(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plans(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupPlans_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py new file mode 100644 index 000000000000..072a7767892c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupPlans +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupPlans_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_backup_plans(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_plans(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupPlans_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py new file mode 100644 index 000000000000..ac9cbae1ed2f --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupVaults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupVaults_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_vaults(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupVaults_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py new file mode 100644 index 000000000000..f6bb058f25db --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackupVaults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackupVaults_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_backup_vaults(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupVaultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_vaults(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackupVaults_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backups_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backups_async.py new file mode 100644 index 000000000000..72b9cc834de7 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backups_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackups_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_backups(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackups_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backups_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backups_sync.py new file mode 100644 index 000000000000..e53f7b1946e6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_backups_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBackups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBackups_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_backups(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBackups_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py new file mode 100644 index 000000000000..33ea7fc69c91 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBindingMatchingResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py new file mode 100644 index 000000000000..ce8cc5a41b4f --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBindingMatchingResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py new file mode 100644 index 000000000000..a413105eae30 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSourceReferences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_data_source_references(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourceReferencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_source_references(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py new file mode 100644 index 000000000000..ec233e277a10 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSourceReferences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_data_source_references(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourceReferencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_source_references(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_sources_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_sources_async.py new file mode 100644 index 000000000000..8c99e5e2f81e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_sources_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListDataSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_data_sources(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListDataSources_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py new file mode 100644 index 000000000000..04e82ab5e461 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListDataSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_data_sources(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListDataSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListDataSources_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_management_servers_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_management_servers_async.py new file mode 100644 index 000000000000..ef7ff5266b08 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_management_servers_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListManagementServers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListManagementServers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_management_servers(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListManagementServersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_management_servers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListManagementServers_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py new file mode 100644 index 000000000000..05004a0445bf --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListManagementServers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListManagementServers_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_management_servers(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListManagementServersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_management_servers(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListManagementServers_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_async.py new file mode 100644 index 000000000000..ab01226b7a5c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListResourceBackupConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDrProtectionSummary_ListResourceBackupConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_list_resource_backup_configs(): + # Create a client + client = backupdr_v1beta.BackupDrProtectionSummaryAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListResourceBackupConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_backup_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDrProtectionSummary_ListResourceBackupConfigs_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_sync.py new file mode 100644 index 000000000000..6add90790048 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListResourceBackupConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDrProtectionSummary_ListResourceBackupConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_list_resource_backup_configs(): + # Create a client + client = backupdr_v1beta.BackupDrProtectionSummaryClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListResourceBackupConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_backup_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDrProtectionSummary_ListResourceBackupConfigs_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_restore_backup_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_restore_backup_async.py new file mode 100644 index 000000000000..0488338d3902 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_restore_backup_async.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_RestoreBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_restore_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + compute_instance_target_environment = ( + backupdr_v1beta.ComputeInstanceTargetEnvironment() + ) + compute_instance_target_environment.project = "project_value" + compute_instance_target_environment.zone = "zone_value" + + request = backupdr_v1beta.RestoreBackupRequest( + compute_instance_target_environment=compute_instance_target_environment, + name="name_value", + ) + + # Make the request + operation = await client.restore_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_RestoreBackup_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_restore_backup_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_restore_backup_sync.py new file mode 100644 index 000000000000..d7c1a1c945db --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_restore_backup_sync.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_RestoreBackup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_restore_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + compute_instance_target_environment = ( + backupdr_v1beta.ComputeInstanceTargetEnvironment() + ) + compute_instance_target_environment.project = "project_value" + compute_instance_target_environment.zone = "zone_value" + + request = backupdr_v1beta.RestoreBackupRequest( + compute_instance_target_environment=compute_instance_target_environment, + name="name_value", + ) + + # Make the request + operation = client.restore_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_RestoreBackup_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_backup_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_backup_async.py new file mode 100644 index 000000000000..d0228abae902 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_backup_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TriggerBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_TriggerBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_trigger_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerBackupRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_TriggerBackup_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py new file mode 100644 index 000000000000..e44b102bb26b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TriggerBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_TriggerBackup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_trigger_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_TriggerBackup_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_async.py new file mode 100644 index 000000000000..0d93e3793ae6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_async.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateAutoProtectionPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1beta.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_sync.py new file mode 100644 index 000000000000..f946d85d872a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_sync.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutoProtectionPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateAutoProtectionPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1beta.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1beta.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_async.py new file mode 100644 index 000000000000..fbe92ec29a03 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_update_backup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupRequest() + + # Make the request + operation = await client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackup_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_association_async.py new file mode 100644 index 000000000000..19c6d531482e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_association_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackupPlanAssociation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_update_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.UpdateBackupPlanAssociationRequest( + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = await client.update_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackupPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_association_sync.py new file mode 100644 index 000000000000..16acfdd53413 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_association_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackupPlanAssociation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackupPlanAssociation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_update_backup_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan_association = backupdr_v1beta.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" + backup_plan_association.resource = "resource_value" + backup_plan_association.backup_plan = "backup_plan_value" + + request = backupdr_v1beta.UpdateBackupPlanAssociationRequest( + backup_plan_association=backup_plan_association, + ) + + # Make the request + operation = client.update_backup_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackupPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_async.py new file mode 100644 index 000000000000..030326fe32e8 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackupPlan_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_update_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.UpdateBackupPlanRequest( + backup_plan=backup_plan, + ) + + # Make the request + operation = await client.update_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackupPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_sync.py new file mode 100644 index 000000000000..da56724f034a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_plan_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackupPlan +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackupPlan_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_update_backup_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + backup_plan = backupdr_v1beta.BackupPlan() + backup_plan.resource_type = "resource_type_value" + backup_plan.backup_vault = "backup_vault_value" + + request = backupdr_v1beta.UpdateBackupPlanRequest( + backup_plan=backup_plan, + ) + + # Make the request + operation = client.update_backup_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackupPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_sync.py new file mode 100644 index 000000000000..48b444d522b0 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_update_backup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupRequest() + + # Make the request + operation = client.update_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackup_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_vault_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_vault_async.py new file mode 100644 index 000000000000..4cefaa4adb9c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_vault_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackupVault_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_update_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupVaultRequest() + + # Make the request + operation = await client.update_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackupVault_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_vault_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_vault_sync.py new file mode 100644 index 000000000000..957028333fc7 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_backup_vault_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBackupVault +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateBackupVault_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_update_backup_vault(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateBackupVaultRequest() + + # Make the request + operation = client.update_backup_vault(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateBackupVault_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_data_source_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_data_source_async.py new file mode 100644 index 000000000000..59e6221a98f2 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_data_source_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateDataSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +async def sample_update_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateDataSourceRequest() + + # Make the request + operation = await client.update_data_source(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateDataSource_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_data_source_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_data_source_sync.py new file mode 100644 index 000000000000..db74337a50d6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_data_source_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateDataSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import backupdr_v1beta + + +def sample_update_data_source(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.UpdateDataSourceRequest() + + # Make the request + operation = client.update_data_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateDataSource_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json index feb76ddf0205..2c750678e2ca 100644 --- a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json +++ b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-backupdr", - "version": "0.10.1" + "version": "0.10.2" }, "snippets": [ { diff --git a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json new file mode 100644 index 000000000000..23b4126311bc --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json @@ -0,0 +1,8233 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.backupdr.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-backupdr", + "version": "0.10.2" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "auto_protection_policy_binding", + "type": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding" + }, + { + "name": "auto_protection_policy_binding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_auto_protection_policy_binding" + }, + "description": "Sample for CreateAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicyBinding_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "auto_protection_policy_binding", + "type": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding" + }, + { + "name": "auto_protection_policy_binding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_auto_protection_policy_binding" + }, + "description": "Sample for CreateAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicyBinding_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy" + }, + { + "name": "auto_protection_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_auto_protection_policy" + }, + "description": "Sample for CreateAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicy_async", + "segments": [ + { + "end": 63, + "start": 27, + "type": "FULL" + }, + { + "end": 63, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 60, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 64, + "start": 61, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateAutoProtectionPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy" + }, + { + "name": "auto_protection_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_auto_protection_policy" + }, + "description": "Sample for CreateAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateAutoProtectionPolicy_sync", + "segments": [ + { + "end": 63, + "start": 27, + "type": "FULL" + }, + { + "end": 63, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 60, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 64, + "start": 61, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_auto_protection_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateBackupPlanAssociationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_plan_association", + "type": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation" + }, + { + "name": "backup_plan_association_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_backup_plan_association" + }, + "description": "Sample for CreateBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_create_backup_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateBackupPlanAssociation_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_backup_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateBackupPlanAssociationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_plan_association", + "type": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation" + }, + { + "name": "backup_plan_association_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_backup_plan_association" + }, + "description": "Sample for CreateBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_create_backup_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateBackupPlanAssociation_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_backup_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateBackupPlanRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_plan", + "type": "google.cloud.backupdr_v1beta.types.BackupPlan" + }, + { + "name": "backup_plan_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_backup_plan" + }, + "description": "Sample for CreateBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_create_backup_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateBackupPlan_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_backup_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateBackupPlanRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_plan", + "type": "google.cloud.backupdr_v1beta.types.BackupPlan" + }, + { + "name": "backup_plan_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_backup_plan" + }, + "description": "Sample for CreateBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_create_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateBackupPlan_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateBackupVaultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_vault", + "type": "google.cloud.backupdr_v1beta.types.BackupVault" + }, + { + "name": "backup_vault_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_backup_vault" + }, + "description": "Sample for CreateBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_create_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateBackupVault_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateBackupVaultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_vault", + "type": "google.cloud.backupdr_v1beta.types.BackupVault" + }, + { + "name": "backup_vault_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_backup_vault" + }, + "description": "Sample for CreateBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_create_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateBackupVault_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateManagementServerRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "management_server", + "type": "google.cloud.backupdr_v1beta.types.ManagementServer" + }, + { + "name": "management_server_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_management_server" + }, + "description": "Sample for CreateManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_create_management_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateManagementServer_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_management_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.CreateManagementServerRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "management_server", + "type": "google.cloud.backupdr_v1beta.types.ManagementServer" + }, + { + "name": "management_server_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_management_server" + }, + "description": "Sample for CreateManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_create_management_server_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateManagementServer_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_create_management_server_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_auto_protection_policy" + }, + "description": "Sample for DeleteAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_auto_protection_policy" + }, + "description": "Sample for DeleteAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup_plan_association" + }, + "description": "Sample for DeleteBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_backup_plan_association" + }, + "description": "Sample for DeleteBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup_plan" + }, + "description": "Sample for DeleteBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_backup_plan" + }, + "description": "Sample for DeleteBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup_vault" + }, + "description": "Sample for DeleteBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupVault_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_backup_vault" + }, + "description": "Sample for DeleteBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupVault_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_management_server" + }, + "description": "Sample for DeleteManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_delete_management_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteManagementServer_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_management_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_management_server" + }, + "description": "Sample for DeleteManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteManagementServer_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_backup_plan_associations_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupPlanAssociationsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupPlanAssociationsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager", + "shortName": "fetch_backup_plan_associations_for_resource_type" + }, + "description": "Sample for FetchBackupPlanAssociationsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupPlanAssociationsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupPlanAssociationsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypePager", + "shortName": "fetch_backup_plan_associations_for_resource_type" + }, + "description": "Sample for FetchBackupPlanAssociationsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_backups_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypeAsyncPager", + "shortName": "fetch_backups_for_resource_type" + }, + "description": "Sample for FetchBackupsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_backups_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypePager", + "shortName": "fetch_backups_for_resource_type" + }, + "description": "Sample for FetchBackupsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_data_source_references_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchDataSourceReferencesForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchDataSourceReferencesForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypeAsyncPager", + "shortName": "fetch_data_source_references_for_resource_type" + }, + "description": "Sample for FetchDataSourceReferencesForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_data_source_references_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchDataSourceReferencesForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchDataSourceReferencesForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypePager", + "shortName": "fetch_data_source_references_for_resource_type" + }, + "description": "Sample for FetchDataSourceReferencesForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_usable_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchUsableBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchUsableBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsAsyncPager", + "shortName": "fetch_usable_backup_vaults" + }, + "description": "Sample for FetchUsableBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_usable_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchUsableBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchUsableBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsPager", + "shortName": "fetch_usable_backup_vaults" + }, + "description": "Sample for FetchUsableBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding", + "shortName": "get_auto_protection_policy_binding" + }, + "description": "Sample for GetAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding", + "shortName": "get_auto_protection_policy_binding" + }, + "description": "Sample for GetAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy", + "shortName": "get_auto_protection_policy" + }, + "description": "Sample for GetAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy", + "shortName": "get_auto_protection_policy" + }, + "description": "Sample for GetAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation", + "shortName": "get_backup_plan_association" + }, + "description": "Sample for GetBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation", + "shortName": "get_backup_plan_association" + }, + "description": "Sample for GetBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan_revision", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanRevision", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanRevision", + "shortName": "get_backup_plan_revision" + }, + "description": "Sample for GetBackupPlanRevision", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_revision", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanRevision", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanRevision", + "shortName": "get_backup_plan_revision" + }, + "description": "Sample for GetBackupPlanRevision", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupPlan", + "shortName": "get_backup_plan" + }, + "description": "Sample for GetBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlan_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupPlan", + "shortName": "get_backup_plan" + }, + "description": "Sample for GetBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlan_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupVaultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupVault", + "shortName": "get_backup_vault" + }, + "description": "Sample for GetBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupVault_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupVaultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BackupVault", + "shortName": "get_backup_vault" + }, + "description": "Sample for GetBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupVault_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackup_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackup_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_binding_matching_resource", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBindingMatchingResource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBindingMatchingResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BindingMatchingResource", + "shortName": "get_binding_matching_resource" + }, + "description": "Sample for GetBindingMatchingResource", + "file": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_binding_matching_resource", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBindingMatchingResource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBindingMatchingResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.BindingMatchingResource", + "shortName": "get_binding_matching_resource" + }, + "description": "Sample for GetBindingMatchingResource", + "file": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_data_source_reference", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSourceReference", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSourceReference" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.DataSourceReference", + "shortName": "get_data_source_reference" + }, + "description": "Sample for GetDataSourceReference", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSourceReference_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_data_source_reference", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSourceReference", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSourceReference" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.DataSourceReference", + "shortName": "get_data_source_reference" + }, + "description": "Sample for GetDataSourceReference", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSourceReference_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_data_source", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.DataSource", + "shortName": "get_data_source" + }, + "description": "Sample for GetDataSource", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_data_source", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.DataSource", + "shortName": "get_data_source" + }, + "description": "Sample for GetDataSource", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetManagementServerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.ManagementServer", + "shortName": "get_management_server" + }, + "description": "Sample for GetManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_get_management_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetManagementServer_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_management_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetManagementServerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.types.ManagementServer", + "shortName": "get_management_server" + }, + "description": "Sample for GetManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_get_management_server_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetManagementServer_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_get_management_server_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.initialize_service", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitializeService", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "InitializeService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.InitializeServiceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "initialize_service" + }, + "description": "Sample for InitializeService", + "file": "backupdr_v1beta_generated_backup_dr_initialize_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitializeService_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_initialize_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.initialize_service", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitializeService", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "InitializeService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.InitializeServiceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "initialize_service" + }, + "description": "Sample for InitializeService", + "file": "backupdr_v1beta_generated_backup_dr_initialize_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitializeService_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_initialize_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.initiate_delete_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "InitiateDeleteAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "initiate_delete_auto_protection_policy_binding" + }, + "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.initiate_delete_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "InitiateDeleteAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "initiate_delete_auto_protection_policy_binding" + }, + "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_applied_auto_protection_policies", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAppliedAutoProtectionPolicies", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListAppliedAutoProtectionPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesAsyncPager", + "shortName": "list_applied_auto_protection_policies" + }, + "description": "Sample for ListAppliedAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_applied_auto_protection_policies", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAppliedAutoProtectionPolicies", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListAppliedAutoProtectionPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesPager", + "shortName": "list_applied_auto_protection_policies" + }, + "description": "Sample for ListAppliedAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_auto_protection_policies", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicies", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListAutoProtectionPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesAsyncPager", + "shortName": "list_auto_protection_policies" + }, + "description": "Sample for ListAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policies", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicies", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListAutoProtectionPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesPager", + "shortName": "list_auto_protection_policies" + }, + "description": "Sample for ListAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_auto_protection_policy_bindings", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicyBindings", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListAutoProtectionPolicyBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsAsyncPager", + "shortName": "list_auto_protection_policy_bindings" + }, + "description": "Sample for ListAutoProtectionPolicyBindings", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policy_bindings", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicyBindings", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListAutoProtectionPolicyBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsPager", + "shortName": "list_auto_protection_policy_bindings" + }, + "description": "Sample for ListAutoProtectionPolicyBindings", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plan_associations", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanAssociations", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupPlanAssociations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsAsyncPager", + "shortName": "list_backup_plan_associations" + }, + "description": "Sample for ListBackupPlanAssociations", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_associations", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanAssociations", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupPlanAssociations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsPager", + "shortName": "list_backup_plan_associations" + }, + "description": "Sample for ListBackupPlanAssociations", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plan_revisions", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanRevisions", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupPlanRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsAsyncPager", + "shortName": "list_backup_plan_revisions" + }, + "description": "Sample for ListBackupPlanRevisions", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_revisions", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanRevisions", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupPlanRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsPager", + "shortName": "list_backup_plan_revisions" + }, + "description": "Sample for ListBackupPlanRevisions", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plans", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlans", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupPlans" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlansRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansAsyncPager", + "shortName": "list_backup_plans" + }, + "description": "Sample for ListBackupPlans", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlans_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plans", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlans", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupPlans" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlansRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansPager", + "shortName": "list_backup_plans" + }, + "description": "Sample for ListBackupPlans", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlans_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsAsyncPager", + "shortName": "list_backup_vaults" + }, + "description": "Sample for ListBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupVaults_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsPager", + "shortName": "list_backup_vaults" + }, + "description": "Sample for ListBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupVaults_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backups", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackups", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "backupdr_v1beta_generated_backup_dr_list_backups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackups_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backups", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackups", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBackups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBackupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsPager", + "shortName": "list_backups" + }, + "description": "Sample for ListBackups", + "file": "backupdr_v1beta_generated_backup_dr_list_backups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackups_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_backups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_binding_matching_resources", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBindingMatchingResources", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBindingMatchingResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesAsyncPager", + "shortName": "list_binding_matching_resources" + }, + "description": "Sample for ListBindingMatchingResources", + "file": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_binding_matching_resources", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBindingMatchingResources", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListBindingMatchingResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesPager", + "shortName": "list_binding_matching_resources" + }, + "description": "Sample for ListBindingMatchingResources", + "file": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_data_source_references", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSourceReferences", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListDataSourceReferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesAsyncPager", + "shortName": "list_data_source_references" + }, + "description": "Sample for ListDataSourceReferences", + "file": "backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_data_source_references", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSourceReferences", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListDataSourceReferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesPager", + "shortName": "list_data_source_references" + }, + "description": "Sample for ListDataSourceReferences", + "file": "backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_data_sources", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSources", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListDataSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListDataSourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesAsyncPager", + "shortName": "list_data_sources" + }, + "description": "Sample for ListDataSources", + "file": "backupdr_v1beta_generated_backup_dr_list_data_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSources_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_data_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_data_sources", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSources", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListDataSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListDataSourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesPager", + "shortName": "list_data_sources" + }, + "description": "Sample for ListDataSources", + "file": "backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSources_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_management_servers", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListManagementServers", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListManagementServers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListManagementServersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersAsyncPager", + "shortName": "list_management_servers" + }, + "description": "Sample for ListManagementServers", + "file": "backupdr_v1beta_generated_backup_dr_list_management_servers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListManagementServers_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_management_servers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_management_servers", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListManagementServers", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "ListManagementServers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListManagementServersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersPager", + "shortName": "list_management_servers" + }, + "description": "Sample for ListManagementServers", + "file": "backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListManagementServers_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.restore_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.RestoreBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "RestoreBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.RestoreBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "restore_backup" + }, + "description": "Sample for RestoreBackup", + "file": "backupdr_v1beta_generated_backup_dr_restore_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_RestoreBackup_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_restore_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.restore_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.RestoreBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "RestoreBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.RestoreBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "restore_backup" + }, + "description": "Sample for RestoreBackup", + "file": "backupdr_v1beta_generated_backup_dr_restore_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_RestoreBackup_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_restore_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.trigger_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "TriggerBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.TriggerBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "rule_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "trigger_backup" + }, + "description": "Sample for TriggerBackup", + "file": "backupdr_v1beta_generated_backup_dr_trigger_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerBackup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_trigger_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.trigger_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "TriggerBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.TriggerBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "rule_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "trigger_backup" + }, + "description": "Sample for TriggerBackup", + "file": "backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerBackup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.update_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateAutoProtectionPolicyRequest" + }, + { + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_auto_protection_policy" + }, + "description": "Sample for UpdateAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateAutoProtectionPolicy_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.update_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateAutoProtectionPolicyRequest" + }, + { + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_auto_protection_policy" + }, + "description": "Sample for UpdateAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateAutoProtectionPolicy_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_auto_protection_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.update_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupPlanAssociationRequest" + }, + { + "name": "backup_plan_association", + "type": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_backup_plan_association" + }, + "description": "Sample for UpdateBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackupPlanAssociation_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.update_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupPlanAssociationRequest" + }, + { + "name": "backup_plan_association", + "type": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_backup_plan_association" + }, + "description": "Sample for UpdateBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackupPlanAssociation_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.update_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupPlanRequest" + }, + { + "name": "backup_plan", + "type": "google.cloud.backupdr_v1beta.types.BackupPlan" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_backup_plan" + }, + "description": "Sample for UpdateBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackupPlan_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.update_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupPlanRequest" + }, + { + "name": "backup_plan", + "type": "google.cloud.backupdr_v1beta.types.BackupPlan" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_backup_plan" + }, + "description": "Sample for UpdateBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackupPlan_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.update_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupVaultRequest" + }, + { + "name": "backup_vault", + "type": "google.cloud.backupdr_v1beta.types.BackupVault" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_backup_vault" + }, + "description": "Sample for UpdateBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackupVault_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.update_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupVaultRequest" + }, + { + "name": "backup_vault", + "type": "google.cloud.backupdr_v1beta.types.BackupVault" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_backup_vault" + }, + "description": "Sample for UpdateBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackupVault_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.update_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.backupdr_v1beta.types.Backup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_backup" + }, + "description": "Sample for UpdateBackup", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackup_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.update_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateBackupRequest" + }, + { + "name": "backup", + "type": "google.cloud.backupdr_v1beta.types.Backup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_backup" + }, + "description": "Sample for UpdateBackup", + "file": "backupdr_v1beta_generated_backup_dr_update_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateBackup_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.update_data_source", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateDataSource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateDataSourceRequest" + }, + { + "name": "data_source", + "type": "google.cloud.backupdr_v1beta.types.DataSource" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_data_source" + }, + "description": "Sample for UpdateDataSource", + "file": "backupdr_v1beta_generated_backup_dr_update_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateDataSource_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.update_data_source", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateDataSource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateDataSourceRequest" + }, + { + "name": "data_source", + "type": "google.cloud.backupdr_v1beta.types.DataSource" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_data_source" + }, + "description": "Sample for UpdateDataSource", + "file": "backupdr_v1beta_generated_backup_dr_update_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateDataSource_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient", + "shortName": "BackupDrProtectionSummaryAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDrProtectionSummaryAsyncClient.list_resource_backup_configs", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary.ListResourceBackupConfigs", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "shortName": "BackupDrProtectionSummary" + }, + "shortName": "ListResourceBackupConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.pagers.ListResourceBackupConfigsAsyncPager", + "shortName": "list_resource_backup_configs" + }, + "description": "Sample for ListResourceBackupConfigs", + "file": "backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDrProtectionSummary_ListResourceBackupConfigs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient", + "shortName": "BackupDrProtectionSummaryClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDrProtectionSummaryClient.list_resource_backup_configs", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary.ListResourceBackupConfigs", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDrProtectionSummary", + "shortName": "BackupDrProtectionSummary" + }, + "shortName": "ListResourceBackupConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.ListResourceBackupConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.pagers.ListResourceBackupConfigsPager", + "shortName": "list_resource_backup_configs" + }, + "description": "Sample for ListResourceBackupConfigs", + "file": "backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDrProtectionSummary_ListResourceBackupConfigs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_protection_summary_list_resource_backup_configs_sync.py" + } + ] +} diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/__init__.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr.py new file mode 100644 index 000000000000..1b1d6133aa72 --- /dev/null +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr.py @@ -0,0 +1,47542 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.any_pb2 as any_pb2 # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import google.type.dayofweek_pb2 as dayofweek_pb2 # type: ignore +import google.type.month_pb2 as month_pb2 # type: ignore +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.backupdr_v1beta.services.backup_dr import ( + BackupDRAsyncClient, + BackupDRClient, + pagers, + transports, +) +from google.cloud.backupdr_v1beta.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, + backupdr, + backupplan, + backupplanassociation, + backupvault, + backupvault_alloydb, + backupvault_ba, + backupvault_cloudsql, + backupvault_disk, + backupvault_gce, + bindingmatchingresource, + datasourcereference, +) + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert BackupDRClient._get_client_cert_source(None, False) is None + assert ( + BackupDRClient._get_client_cert_source(mock_provided_cert_source, False) is None + ) + assert ( + BackupDRClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + BackupDRClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + BackupDRClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = BackupDRClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = BackupDRClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BackupDRClient, "grpc"), + (BackupDRAsyncClient, "grpc_asyncio"), + (BackupDRClient, "rest"), + ], +) +def test_backup_dr_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "backupdr.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.BackupDRGrpcTransport, "grpc"), + (transports.BackupDRGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BackupDRRestTransport, "rest"), + ], +) +def test_backup_dr_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BackupDRClient, "grpc"), + (BackupDRAsyncClient, "grpc_asyncio"), + (BackupDRClient, "rest"), + ], +) +def test_backup_dr_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "backupdr.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com" + ) + + +def test_backup_dr_client_get_transport_class(): + transport = BackupDRClient.get_transport_class() + available_transports = [ + transports.BackupDRGrpcTransport, + transports.BackupDRRestTransport, + ] + assert transport in available_transports + + transport = BackupDRClient.get_transport_class("grpc") + assert transport == transports.BackupDRGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (BackupDRClient, transports.BackupDRGrpcTransport, "grpc"), + (BackupDRAsyncClient, transports.BackupDRGrpcAsyncIOTransport, "grpc_asyncio"), + (BackupDRClient, transports.BackupDRRestTransport, "rest"), + ], +) +@mock.patch.object( + BackupDRClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDRClient), +) +@mock.patch.object( + BackupDRAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDRAsyncClient), +) +def test_backup_dr_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(BackupDRClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(BackupDRClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (BackupDRClient, transports.BackupDRGrpcTransport, "grpc", "true"), + ( + BackupDRAsyncClient, + transports.BackupDRGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (BackupDRClient, transports.BackupDRGrpcTransport, "grpc", "false"), + ( + BackupDRAsyncClient, + transports.BackupDRGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (BackupDRClient, transports.BackupDRRestTransport, "rest", "true"), + (BackupDRClient, transports.BackupDRRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + BackupDRClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDRClient), +) +@mock.patch.object( + BackupDRAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDRAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_backup_dr_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [BackupDRClient, BackupDRAsyncClient]) +@mock.patch.object( + BackupDRClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BackupDRClient) +) +@mock.patch.object( + BackupDRAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(BackupDRAsyncClient), +) +def test_backup_dr_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [BackupDRClient, BackupDRAsyncClient]) +@mock.patch.object( + BackupDRClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDRClient), +) +@mock.patch.object( + BackupDRAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDRAsyncClient), +) +def test_backup_dr_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = BackupDRClient._DEFAULT_UNIVERSE + default_endpoint = BackupDRClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = BackupDRClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (BackupDRClient, transports.BackupDRGrpcTransport, "grpc"), + (BackupDRAsyncClient, transports.BackupDRGrpcAsyncIOTransport, "grpc_asyncio"), + (BackupDRClient, transports.BackupDRRestTransport, "rest"), + ], +) +def test_backup_dr_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (BackupDRClient, transports.BackupDRGrpcTransport, "grpc", grpc_helpers), + ( + BackupDRAsyncClient, + transports.BackupDRGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (BackupDRClient, transports.BackupDRRestTransport, "rest", None), + ], +) +def test_backup_dr_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_backup_dr_client_client_options_from_dict(): + with mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr.transports.BackupDRGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = BackupDRClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (BackupDRClient, transports.BackupDRGrpcTransport, "grpc", grpc_helpers), + ( + BackupDRAsyncClient, + transports.BackupDRGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_backup_dr_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "backupdr.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="backupdr.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.ListManagementServersRequest(), + {}, + ], +) +def test_list_management_servers(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupdr.ListManagementServersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_management_servers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupdr.ListManagementServersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListManagementServersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_management_servers_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupdr.ListManagementServersRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_management_servers(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_management_servers_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_management_servers + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_management_servers + ] = mock_rpc + request = {} + client.list_management_servers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_management_servers(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_management_servers_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_management_servers + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_management_servers + ] = mock_rpc + + request = {} + await client.list_management_servers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_management_servers(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupdr.ListManagementServersRequest(), + {}, + ], +) +async def test_list_management_servers_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ListManagementServersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_management_servers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupdr.ListManagementServersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListManagementServersAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_management_servers_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.ListManagementServersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + call.return_value = backupdr.ListManagementServersResponse() + client.list_management_servers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_management_servers_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.ListManagementServersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ListManagementServersResponse() + ) + await client.list_management_servers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_management_servers_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupdr.ListManagementServersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_management_servers( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_management_servers_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_management_servers( + backupdr.ListManagementServersRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_management_servers_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupdr.ListManagementServersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ListManagementServersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_management_servers( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_management_servers_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_management_servers( + backupdr.ListManagementServersRequest(), + parent="parent_value", + ) + + +def test_list_management_servers_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + next_page_token="abc", + ), + backupdr.ListManagementServersResponse( + management_servers=[], + next_page_token="def", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + ], + next_page_token="ghi", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_management_servers(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupdr.ManagementServer) for i in results) + + +def test_list_management_servers_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + next_page_token="abc", + ), + backupdr.ListManagementServersResponse( + management_servers=[], + next_page_token="def", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + ], + next_page_token="ghi", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + ), + RuntimeError, + ) + pages = list(client.list_management_servers(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_management_servers_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + next_page_token="abc", + ), + backupdr.ListManagementServersResponse( + management_servers=[], + next_page_token="def", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + ], + next_page_token="ghi", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_management_servers( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupdr.ManagementServer) for i in responses) + + +@pytest.mark.asyncio +async def test_list_management_servers_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + next_page_token="abc", + ), + backupdr.ListManagementServersResponse( + management_servers=[], + next_page_token="def", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + ], + next_page_token="ghi", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_management_servers(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.GetManagementServerRequest(), + {}, + ], +) +def test_get_management_server(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=True, + ) + response = client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupdr.GetManagementServerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupdr.ManagementServer) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.type_ == backupdr.ManagementServer.InstanceType.BACKUP_RESTORE + assert response.state == backupdr.ManagementServer.InstanceState.CREATING + assert response.etag == "etag_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.ba_proxy_uri == ["ba_proxy_uri_value"] + assert response.satisfies_pzi is True + + +def test_get_management_server_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupdr.GetManagementServerRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_management_server(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_management_server_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_management_server + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_management_server] = ( + mock_rpc + ) + request = {} + client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_management_server_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_management_server + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_management_server + ] = mock_rpc + + request = {} + await client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupdr.GetManagementServerRequest(), + {}, + ], +) +async def test_get_management_server_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=True, + ) + ) + response = await client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupdr.GetManagementServerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupdr.ManagementServer) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.type_ == backupdr.ManagementServer.InstanceType.BACKUP_RESTORE + assert response.state == backupdr.ManagementServer.InstanceState.CREATING + assert response.etag == "etag_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.ba_proxy_uri == ["ba_proxy_uri_value"] + assert response.satisfies_pzi is True + + +def test_get_management_server_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.GetManagementServerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + call.return_value = backupdr.ManagementServer() + client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_management_server_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.GetManagementServerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ManagementServer() + ) + await client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_management_server_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupdr.ManagementServer() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_management_server( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_management_server_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_management_server( + backupdr.GetManagementServerRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_management_server_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupdr.ManagementServer() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ManagementServer() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_management_server( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_management_server_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_management_server( + backupdr.GetManagementServerRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.CreateManagementServerRequest(), + {}, + ], +) +def test_create_management_server(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupdr.CreateManagementServerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_management_server_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupdr.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + request_id="request_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_management_server(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + request_id="request_id_value", + ) + assert args[0] == request_msg + + +def test_create_management_server_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_management_server + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_management_server + ] = mock_rpc + request = {} + client.create_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_management_server_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_management_server + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_management_server + ] = mock_rpc + + request = {} + await client.create_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupdr.CreateManagementServerRequest(), + {}, + ], +) +async def test_create_management_server_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupdr.CreateManagementServerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_management_server_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.CreateManagementServerRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_management_server_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.CreateManagementServerRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_management_server_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_management_server( + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].management_server + mock_val = backupdr.ManagementServer(name="name_value") + assert arg == mock_val + arg = args[0].management_server_id + mock_val = "management_server_id_value" + assert arg == mock_val + + +def test_create_management_server_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_management_server( + backupdr.CreateManagementServerRequest(), + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_management_server_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_management_server( + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].management_server + mock_val = backupdr.ManagementServer(name="name_value") + assert arg == mock_val + arg = args[0].management_server_id + mock_val = "management_server_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_management_server_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_management_server( + backupdr.CreateManagementServerRequest(), + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.DeleteManagementServerRequest(), + {}, + ], +) +def test_delete_management_server(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupdr.DeleteManagementServerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_management_server_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupdr.DeleteManagementServerRequest( + name="name_value", + request_id="request_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_management_server(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest( + name="name_value", + request_id="request_id_value", + ) + assert args[0] == request_msg + + +def test_delete_management_server_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_management_server + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_management_server + ] = mock_rpc + request = {} + client.delete_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_management_server_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_management_server + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_management_server + ] = mock_rpc + + request = {} + await client.delete_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupdr.DeleteManagementServerRequest(), + {}, + ], +) +async def test_delete_management_server_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupdr.DeleteManagementServerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_management_server_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.DeleteManagementServerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_management_server_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.DeleteManagementServerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_management_server_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_management_server( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_management_server_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_management_server( + backupdr.DeleteManagementServerRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_management_server_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_management_server( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_management_server_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_management_server( + backupdr.DeleteManagementServerRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.CreateBackupVaultRequest(), + {}, + ], +) +def test_create_backup_vault(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.CreateBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_vault_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_backup_vault(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) + assert args[0] == request_msg + + +def test_create_backup_vault_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_backup_vault in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_backup_vault] = ( + mock_rpc + ) + request = {} + client.create_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_backup_vault_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_backup_vault + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_backup_vault + ] = mock_rpc + + request = {} + await client.create_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.CreateBackupVaultRequest(), + {}, + ], +) +async def test_create_backup_vault_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.CreateBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_vault_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.CreateBackupVaultRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_backup_vault_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.CreateBackupVaultRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_backup_vault_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_backup_vault( + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].backup_vault + mock_val = backupvault.BackupVault(name="name_value") + assert arg == mock_val + arg = args[0].backup_vault_id + mock_val = "backup_vault_id_value" + assert arg == mock_val + + +def test_create_backup_vault_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_backup_vault( + backupvault.CreateBackupVaultRequest(), + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_backup_vault_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_backup_vault( + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].backup_vault + mock_val = backupvault.BackupVault(name="name_value") + assert arg == mock_val + arg = args[0].backup_vault_id + mock_val = "backup_vault_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_backup_vault_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_backup_vault( + backupvault.CreateBackupVaultRequest(), + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupVaultsRequest(), + {}, + ], +) +def test_list_backup_vaults(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.ListBackupVaultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupVaultsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_vaults_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.ListBackupVaultsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_backup_vaults(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_backup_vaults_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_backup_vaults in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_backup_vaults] = ( + mock_rpc + ) + request = {} + client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_vaults(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_backup_vaults_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_backup_vaults + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_backup_vaults + ] = mock_rpc + + request = {} + await client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_backup_vaults(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupVaultsRequest(), + {}, + ], +) +async def test_list_backup_vaults_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.ListBackupVaultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupVaultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_vaults_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.ListBackupVaultsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.ListBackupVaultsResponse() + client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_backup_vaults_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.ListBackupVaultsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupVaultsResponse() + ) + await client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_backup_vaults_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListBackupVaultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backup_vaults( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_backup_vaults_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_vaults( + backupvault.ListBackupVaultsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_backup_vaults_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListBackupVaultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupVaultsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backup_vaults( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_backup_vaults_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backup_vaults( + backupvault.ListBackupVaultsRequest(), + parent="parent_value", + ) + + +def test_list_backup_vaults_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backup_vaults(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in results) + + +def test_list_backup_vaults_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backup_vaults(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_backup_vaults_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backup_vaults( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in responses) + + +@pytest.mark.asyncio +async def test_list_backup_vaults_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backup_vaults(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchUsableBackupVaultsRequest(), + {}, + ], +) +def test_fetch_usable_backup_vaults(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.FetchUsableBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.FetchUsableBackupVaultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchUsableBackupVaultsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_fetch_usable_backup_vaults_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.FetchUsableBackupVaultsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_usable_backup_vaults(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_fetch_usable_backup_vaults_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_usable_backup_vaults + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_usable_backup_vaults + ] = mock_rpc + request = {} + client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_usable_backup_vaults(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_fetch_usable_backup_vaults_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.fetch_usable_backup_vaults + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.fetch_usable_backup_vaults + ] = mock_rpc + + request = {} + await client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_usable_backup_vaults(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchUsableBackupVaultsRequest(), + {}, + ], +) +async def test_fetch_usable_backup_vaults_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchUsableBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.FetchUsableBackupVaultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchUsableBackupVaultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_fetch_usable_backup_vaults_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.FetchUsableBackupVaultsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.FetchUsableBackupVaultsResponse() + client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_fetch_usable_backup_vaults_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.FetchUsableBackupVaultsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchUsableBackupVaultsResponse() + ) + await client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_fetch_usable_backup_vaults_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.FetchUsableBackupVaultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_usable_backup_vaults( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_fetch_usable_backup_vaults_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_usable_backup_vaults( + backupvault.FetchUsableBackupVaultsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_fetch_usable_backup_vaults_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.FetchUsableBackupVaultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchUsableBackupVaultsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_usable_backup_vaults( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_fetch_usable_backup_vaults_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.fetch_usable_backup_vaults( + backupvault.FetchUsableBackupVaultsRequest(), + parent="parent_value", + ) + + +def test_fetch_usable_backup_vaults_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.fetch_usable_backup_vaults( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in results) + + +def test_fetch_usable_backup_vaults_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_usable_backup_vaults(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_fetch_usable_backup_vaults_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_usable_backup_vaults( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_usable_backup_vaults_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.fetch_usable_backup_vaults(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupVaultRequest(), + {}, + ], +) +def test_get_backup_vault(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + response = client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.GetBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.BackupVault) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.deletable is True + assert response.etag == "etag_value" + assert response.state == backupvault.BackupVault.State.CREATING + assert response.backup_count == 1278 + assert response.service_account == "service_account_value" + assert response.total_stored_bytes == 1946 + assert response.uid == "uid_value" + assert ( + response.access_restriction + == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT + ) + + +def test_get_backup_vault_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.GetBackupVaultRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_backup_vault(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_backup_vault_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_backup_vault in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_backup_vault] = ( + mock_rpc + ) + request = {} + client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_backup_vault_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_backup_vault + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_backup_vault + ] = mock_rpc + + request = {} + await client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupVaultRequest(), + {}, + ], +) +async def test_get_backup_vault_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + ) + response = await client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.GetBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.BackupVault) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.deletable is True + assert response.etag == "etag_value" + assert response.state == backupvault.BackupVault.State.CREATING + assert response.backup_count == 1278 + assert response.service_account == "service_account_value" + assert response.total_stored_bytes == 1946 + assert response.uid == "uid_value" + assert ( + response.access_restriction + == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT + ) + + +def test_get_backup_vault_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.GetBackupVaultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + call.return_value = backupvault.BackupVault() + client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_backup_vault_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.GetBackupVaultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.BackupVault() + ) + await client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_backup_vault_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.BackupVault() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup_vault( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_backup_vault_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_vault( + backupvault.GetBackupVaultRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_backup_vault_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.BackupVault() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.BackupVault() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup_vault( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_backup_vault_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup_vault( + backupvault.GetBackupVaultRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupVaultRequest(), + {}, + ], +) +def test_update_backup_vault(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.UpdateBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_vault_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.UpdateBackupVaultRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_backup_vault(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + assert args[0] == request_msg + + +def test_update_backup_vault_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_backup_vault in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_backup_vault] = ( + mock_rpc + ) + request = {} + client.update_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_backup_vault_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_backup_vault + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_backup_vault + ] = mock_rpc + + request = {} + await client.update_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupVaultRequest(), + {}, + ], +) +async def test_update_backup_vault_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.UpdateBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_vault_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.UpdateBackupVaultRequest() + + request.backup_vault.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup_vault.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_backup_vault_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.UpdateBackupVaultRequest() + + request.backup_vault.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup_vault.name=name_value", + ) in kw["metadata"] + + +def test_update_backup_vault_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_backup_vault( + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].backup_vault + mock_val = backupvault.BackupVault(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_backup_vault_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup_vault( + backupvault.UpdateBackupVaultRequest(), + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_backup_vault_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_backup_vault( + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].backup_vault + mock_val = backupvault.BackupVault(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_backup_vault_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_backup_vault( + backupvault.UpdateBackupVaultRequest(), + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupVaultRequest(), + {}, + ], +) +def test_delete_backup_vault(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.DeleteBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_vault_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.DeleteBackupVaultRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_backup_vault(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest( + name="name_value", + etag="etag_value", + ) + assert args[0] == request_msg + + +def test_delete_backup_vault_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_backup_vault in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_backup_vault] = ( + mock_rpc + ) + request = {} + client.delete_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_backup_vault_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_backup_vault + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_backup_vault + ] = mock_rpc + + request = {} + await client.delete_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupVaultRequest(), + {}, + ], +) +async def test_delete_backup_vault_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.DeleteBackupVaultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_vault_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.DeleteBackupVaultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_backup_vault_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.DeleteBackupVaultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_backup_vault_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup_vault( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_backup_vault_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup_vault( + backupvault.DeleteBackupVaultRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_backup_vault_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup_vault( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_backup_vault_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_backup_vault( + backupvault.DeleteBackupVaultRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListDataSourcesRequest(), + {}, + ], +) +def test_list_data_sources(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.ListDataSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_data_sources_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.ListDataSourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_data_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_data_sources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_sources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_data_sources] = ( + mock_rpc + ) + request = {} + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_data_sources_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_data_sources + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_data_sources + ] = mock_rpc + + request = {} + await client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_data_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListDataSourcesRequest(), + {}, + ], +) +async def test_list_data_sources_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.ListDataSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_data_sources_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.ListDataSourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + call.return_value = backupvault.ListDataSourcesResponse() + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_data_sources_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.ListDataSourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListDataSourcesResponse() + ) + await client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_data_sources_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListDataSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_sources( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_data_sources_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_sources( + backupvault.ListDataSourcesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_data_sources_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListDataSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListDataSourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_sources( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_data_sources_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_data_sources( + backupvault.ListDataSourcesRequest(), + parent="parent_value", + ) + + +def test_list_data_sources_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_data_sources(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.DataSource) for i in results) + + +def test_list_data_sources_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_sources(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_data_sources_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_sources( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupvault.DataSource) for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_sources_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_data_sources(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetDataSourceRequest(), + {}, + ], +) +def test_get_data_source(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) + response = client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.GetDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.DataSource) + assert response.name == "name_value" + assert response.state == backupvault.DataSource.State.CREATING + assert response.backup_count == 1278 + assert response.etag == "etag_value" + assert response.total_stored_bytes == 1946 + assert response.config_state == backupvault.BackupConfigState.ACTIVE + assert response.backup_blocked_by_vault_access_restriction is True + + +def test_get_data_source_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.GetDataSourceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_data_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_data_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_data_source] = mock_rpc + request = {} + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_data_source_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_data_source + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_data_source + ] = mock_rpc + + request = {} + await client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetDataSourceRequest(), + {}, + ], +) +async def test_get_data_source_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) + ) + response = await client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.GetDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.DataSource) + assert response.name == "name_value" + assert response.state == backupvault.DataSource.State.CREATING + assert response.backup_count == 1278 + assert response.etag == "etag_value" + assert response.total_stored_bytes == 1946 + assert response.config_state == backupvault.BackupConfigState.ACTIVE + assert response.backup_blocked_by_vault_access_restriction is True + + +def test_get_data_source_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.GetDataSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + call.return_value = backupvault.DataSource() + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_data_source_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.GetDataSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.DataSource() + ) + await client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_data_source_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.DataSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_source( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_data_source_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_source( + backupvault.GetDataSourceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_data_source_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.DataSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.DataSource() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_source( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_data_source_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_source( + backupvault.GetDataSourceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateDataSourceRequest(), + {}, + ], +) +def test_update_data_source(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.UpdateDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_data_source_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.UpdateDataSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_data_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + assert args[0] == request_msg + + +def test_update_data_source_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_data_source in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_data_source] = ( + mock_rpc + ) + request = {} + client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_data_source_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_data_source + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_data_source + ] = mock_rpc + + request = {} + await client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateDataSourceRequest(), + {}, + ], +) +async def test_update_data_source_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.UpdateDataSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_data_source_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.UpdateDataSourceRequest() + + request.data_source.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "data_source.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_data_source_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.UpdateDataSourceRequest() + + request.data_source.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "data_source.name=name_value", + ) in kw["metadata"] + + +def test_update_data_source_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_source( + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_source + mock_val = backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_data_source_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_source( + backupvault.UpdateDataSourceRequest(), + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_data_source_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_source( + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_source + mock_val = backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_data_source_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_data_source( + backupvault.UpdateDataSourceRequest(), + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupsRequest(), + {}, + ], +) +def test_list_backups(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.ListBackupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backups_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.ListBackupsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_backups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_backups_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_backups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc + request = {} + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_backups_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_backups + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_backups + ] = mock_rpc + + request = {} + await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_backups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupsRequest(), + {}, + ], +) +async def test_list_backups_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.ListBackupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backups_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.ListBackupsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = backupvault.ListBackupsResponse() + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_backups_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.ListBackupsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupsResponse() + ) + await client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_backups_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListBackupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backups( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_backups_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backups( + backupvault.ListBackupsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backups( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_backups_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backups( + backupvault.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backups(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.Backup) for i in results) + + +def test_list_backups_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backups(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_backups_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backups( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupvault.Backup) for i in responses) + + +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backups(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchBackupsForResourceTypeRequest(), + {}, + ], +) +def test_fetch_backups_for_resource_type(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + response = client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.FetchBackupsForResourceTypeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchBackupsForResourceTypePager) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_backups_for_resource_type_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.FetchBackupsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_backups_for_resource_type(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_fetch_backups_for_resource_type_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_backups_for_resource_type + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_backups_for_resource_type + ] = mock_rpc + request = {} + client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backups_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_fetch_backups_for_resource_type_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.fetch_backups_for_resource_type + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.fetch_backups_for_resource_type + ] = mock_rpc + + request = {} + await client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_backups_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchBackupsForResourceTypeRequest(), + {}, + ], +) +async def test_fetch_backups_for_resource_type_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.FetchBackupsForResourceTypeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchBackupsForResourceTypeAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_backups_for_resource_type_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.FetchBackupsForResourceTypeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_fetch_backups_for_resource_type_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.FetchBackupsForResourceTypeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchBackupsForResourceTypeResponse() + ) + await client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_fetch_backups_for_resource_type_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_backups_for_resource_type( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" + assert arg == mock_val + + +def test_fetch_backups_for_resource_type_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_backups_for_resource_type( + backupvault.FetchBackupsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +@pytest.mark.asyncio +async def test_fetch_backups_for_resource_type_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchBackupsForResourceTypeResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_backups_for_resource_type( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_fetch_backups_for_resource_type_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.fetch_backups_for_resource_type( + backupvault.FetchBackupsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backups_for_resource_type_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], + next_page_token="def", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.fetch_backups_for_resource_type( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.Backup) for i in results) + + +def test_fetch_backups_for_resource_type_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], + next_page_token="def", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_backups_for_resource_type(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_fetch_backups_for_resource_type_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], + next_page_token="def", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_backups_for_resource_type( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupvault.Backup) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_backups_for_resource_type_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], + next_page_token="def", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.fetch_backups_for_resource_type(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupRequest(), + {}, + ], +) +def test_get_backup(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_value"], + ) + response = client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.GetBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.Backup) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.etag == "etag_value" + assert response.state == backupvault.Backup.State.CREATING + assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED + assert response.resource_size_bytes == 2056 + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.kms_key_versions == ["kms_key_versions_value"] + + +def test_get_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.GetBackupRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_backup(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_backup_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_backup] = mock_rpc + request = {} + client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_backup + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_backup + ] = mock_rpc + + request = {} + await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupRequest(), + {}, + ], +) +async def test_get_backup_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_value"], + ) + ) + response = await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.GetBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.Backup) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.etag == "etag_value" + assert response.state == backupvault.Backup.State.CREATING + assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED + assert response.resource_size_bytes == 2056 + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.kms_key_versions == ["kms_key_versions_value"] + + +def test_get_backup_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.GetBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = backupvault.Backup() + client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_backup_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.GetBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(backupvault.Backup()) + await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_backup_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.Backup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_backup_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup( + backupvault.GetBackupRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupvault.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(backupvault.Backup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_backup_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup( + backupvault.GetBackupRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupRequest(), + {}, + ], +) +def test_update_backup(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.UpdateBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.UpdateBackupRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_backup(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + assert args[0] == request_msg + + +def test_update_backup_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_backup] = mock_rpc + request = {} + client.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_backup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_backup + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_backup + ] = mock_rpc + + request = {} + await client.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupRequest(), + {}, + ], +) +async def test_update_backup_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.UpdateBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.UpdateBackupRequest() + + request.backup.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_backup_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.UpdateBackupRequest() + + request.backup.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup.name=name_value", + ) in kw["metadata"] + + +def test_update_backup_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_backup( + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].backup + mock_val = backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_backup_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup( + backupvault.UpdateBackupRequest(), + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_backup_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_backup( + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].backup + mock_val = backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_backup_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_backup( + backupvault.UpdateBackupRequest(), + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupRequest(), + {}, + ], +) +def test_delete_backup(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.DeleteBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.DeleteBackupRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_backup(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_backup_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_backup] = mock_rpc + request = {} + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_backup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_backup + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_backup + ] = mock_rpc + + request = {} + await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupRequest(), + {}, + ], +) +async def test_delete_backup_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.DeleteBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.DeleteBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_backup_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.DeleteBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_backup_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_backup_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup( + backupvault.DeleteBackupRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_backup_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_backup_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_backup( + backupvault.DeleteBackupRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.RestoreBackupRequest(), + {}, + ], +) +def test_restore_backup(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.restore_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupvault.RestoreBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupvault.RestoreBackupRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.restore_backup(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_restore_backup_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.restore_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.restore_backup] = mock_rpc + request = {} + client.restore_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.restore_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_restore_backup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.restore_backup + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.restore_backup + ] = mock_rpc + + request = {} + await client.restore_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.restore_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupvault.RestoreBackupRequest(), + {}, + ], +) +async def test_restore_backup_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.restore_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupvault.RestoreBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_backup_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.RestoreBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_restore_backup_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupvault.RestoreBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.restore_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_restore_backup_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_backup( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_restore_backup_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_backup( + backupvault.RestoreBackupRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_restore_backup_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_backup( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_restore_backup_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_backup( + backupvault.RestoreBackupRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.CreateBackupPlanRequest(), + {}, + ], +) +def test_create_backup_plan(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.CreateBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_plan_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplan.CreateBackupPlanRequest( + parent="parent_value", + backup_plan_id="backup_plan_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_backup_plan(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest( + parent="parent_value", + backup_plan_id="backup_plan_id_value", + ) + assert args[0] == request_msg + + +def test_create_backup_plan_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_backup_plan in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_backup_plan] = ( + mock_rpc + ) + request = {} + client.create_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_backup_plan_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_backup_plan + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_backup_plan + ] = mock_rpc + + request = {} + await client.create_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplan.CreateBackupPlanRequest(), + {}, + ], +) +async def test_create_backup_plan_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplan.CreateBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_plan_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.CreateBackupPlanRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_backup_plan_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.CreateBackupPlanRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_backup_plan_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_backup_plan( + parent="parent_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + assert arg == mock_val + arg = args[0].backup_plan_id + mock_val = "backup_plan_id_value" + assert arg == mock_val + + +def test_create_backup_plan_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_backup_plan( + backupplan.CreateBackupPlanRequest(), + parent="parent_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_backup_plan_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_backup_plan( + parent="parent_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + assert arg == mock_val + arg = args[0].backup_plan_id + mock_val = "backup_plan_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_backup_plan_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_backup_plan( + backupplan.CreateBackupPlanRequest(), + parent="parent_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.UpdateBackupPlanRequest(), + {}, + ], +) +def test_update_backup_plan(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.UpdateBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_plan_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplan.UpdateBackupPlanRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_backup_plan(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + assert args[0] == request_msg + + +def test_update_backup_plan_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_backup_plan in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_backup_plan] = ( + mock_rpc + ) + request = {} + client.update_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_backup_plan_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_backup_plan + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_backup_plan + ] = mock_rpc + + request = {} + await client.update_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplan.UpdateBackupPlanRequest(), + {}, + ], +) +async def test_update_backup_plan_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplan.UpdateBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_plan_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.UpdateBackupPlanRequest() + + request.backup_plan.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup_plan.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_backup_plan_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.UpdateBackupPlanRequest() + + request.backup_plan.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup_plan.name=name_value", + ) in kw["metadata"] + + +def test_update_backup_plan_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_backup_plan( + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_backup_plan_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup_plan( + backupplan.UpdateBackupPlanRequest(), + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_backup_plan_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_backup_plan( + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_backup_plan_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_backup_plan( + backupplan.UpdateBackupPlanRequest(), + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRequest(), + {}, + ], +) +def test_get_backup_plan(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.BackupPlan( + name="name_value", + description="description_value", + max_custom_on_demand_retention_days=3723, + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) + response = client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.GetBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.max_custom_on_demand_retention_days == 3723 + assert response.state == backupplan.BackupPlan.State.CREATING + assert response.resource_type == "resource_type_value" + assert response.etag == "etag_value" + assert response.backup_vault == "backup_vault_value" + assert response.backup_vault_service_account == "backup_vault_service_account_value" + assert response.log_retention_days == 1929 + assert response.supported_resource_types == ["supported_resource_types_value"] + assert response.revision_id == "revision_id_value" + assert response.revision_name == "revision_name_value" + + +def test_get_backup_plan_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplan.GetBackupPlanRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_backup_plan(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_backup_plan_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_backup_plan in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_backup_plan] = mock_rpc + request = {} + client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_backup_plan_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_backup_plan + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_backup_plan + ] = mock_rpc + + request = {} + await client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRequest(), + {}, + ], +) +async def test_get_backup_plan_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlan( + name="name_value", + description="description_value", + max_custom_on_demand_retention_days=3723, + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) + ) + response = await client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplan.GetBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.max_custom_on_demand_retention_days == 3723 + assert response.state == backupplan.BackupPlan.State.CREATING + assert response.resource_type == "resource_type_value" + assert response.etag == "etag_value" + assert response.backup_vault == "backup_vault_value" + assert response.backup_vault_service_account == "backup_vault_service_account_value" + assert response.log_retention_days == 1929 + assert response.supported_resource_types == ["supported_resource_types_value"] + assert response.revision_id == "revision_id_value" + assert response.revision_name == "revision_name_value" + + +def test_get_backup_plan_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.GetBackupPlanRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + call.return_value = backupplan.BackupPlan() + client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_backup_plan_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.GetBackupPlanRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlan() + ) + await client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_backup_plan_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.BackupPlan() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup_plan( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_backup_plan_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_plan( + backupplan.GetBackupPlanRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_backup_plan_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.BackupPlan() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlan() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup_plan( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_backup_plan_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup_plan( + backupplan.GetBackupPlanRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlansRequest(), + {}, + ], +) +def test_list_backup_plans(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.ListBackupPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.ListBackupPlansRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlansPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_plans_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplan.ListBackupPlansRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_backup_plans(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_backup_plans_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_backup_plans in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_backup_plans] = ( + mock_rpc + ) + request = {} + client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plans(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_backup_plans_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_backup_plans + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_backup_plans + ] = mock_rpc + + request = {} + await client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_backup_plans(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlansRequest(), + {}, + ], +) +async def test_list_backup_plans_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplan.ListBackupPlansRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlansAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_plans_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.ListBackupPlansRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlansResponse() + client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_backup_plans_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.ListBackupPlansRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlansResponse() + ) + await client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_backup_plans_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.ListBackupPlansResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backup_plans( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_backup_plans_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_plans( + backupplan.ListBackupPlansRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_backup_plans_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.ListBackupPlansResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlansResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backup_plans( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_backup_plans_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backup_plans( + backupplan.ListBackupPlansRequest(), + parent="parent_value", + ) + + +def test_list_backup_plans_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[], + next_page_token="def", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backup_plans(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupplan.BackupPlan) for i in results) + + +def test_list_backup_plans_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[], + next_page_token="def", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backup_plans(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_backup_plans_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[], + next_page_token="def", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backup_plans( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupplan.BackupPlan) for i in responses) + + +@pytest.mark.asyncio +async def test_list_backup_plans_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[], + next_page_token="def", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backup_plans(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.DeleteBackupPlanRequest(), + {}, + ], +) +def test_delete_backup_plan(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.DeleteBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_plan_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplan.DeleteBackupPlanRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_backup_plan(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_backup_plan_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_backup_plan in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_backup_plan] = ( + mock_rpc + ) + request = {} + client.delete_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_backup_plan_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_backup_plan + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_backup_plan + ] = mock_rpc + + request = {} + await client.delete_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplan.DeleteBackupPlanRequest(), + {}, + ], +) +async def test_delete_backup_plan_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplan.DeleteBackupPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_plan_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.DeleteBackupPlanRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_backup_plan_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.DeleteBackupPlanRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_backup_plan_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup_plan( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_backup_plan_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup_plan( + backupplan.DeleteBackupPlanRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_backup_plan_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup_plan( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_backup_plan_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_backup_plan( + backupplan.DeleteBackupPlanRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRevisionRequest(), + {}, + ], +) +def test_get_backup_plan_revision(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + response = client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.GetBackupPlanRevisionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlanRevision) + assert response.name == "name_value" + assert response.revision_id == "revision_id_value" + assert response.state == backupplan.BackupPlanRevision.State.CREATING + + +def test_get_backup_plan_revision_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplan.GetBackupPlanRevisionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_backup_plan_revision(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_backup_plan_revision_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_backup_plan_revision + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_backup_plan_revision + ] = mock_rpc + request = {} + client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_revision(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_backup_plan_revision_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_backup_plan_revision + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_backup_plan_revision + ] = mock_rpc + + request = {} + await client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_backup_plan_revision(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRevisionRequest(), + {}, + ], +) +async def test_get_backup_plan_revision_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + ) + response = await client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplan.GetBackupPlanRevisionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlanRevision) + assert response.name == "name_value" + assert response.revision_id == "revision_id_value" + assert response.state == backupplan.BackupPlanRevision.State.CREATING + + +def test_get_backup_plan_revision_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.GetBackupPlanRevisionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + call.return_value = backupplan.BackupPlanRevision() + client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_backup_plan_revision_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.GetBackupPlanRevisionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlanRevision() + ) + await client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_backup_plan_revision_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.BackupPlanRevision() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup_plan_revision( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_backup_plan_revision_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_plan_revision( + backupplan.GetBackupPlanRevisionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_backup_plan_revision_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.BackupPlanRevision() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlanRevision() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup_plan_revision( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_backup_plan_revision_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup_plan_revision( + backupplan.GetBackupPlanRevisionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlanRevisionsRequest(), + {}, + ], +) +def test_list_backup_plan_revisions(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.ListBackupPlanRevisionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlanRevisionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_plan_revisions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplan.ListBackupPlanRevisionsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_backup_plan_revisions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_backup_plan_revisions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_backup_plan_revisions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_backup_plan_revisions + ] = mock_rpc + request = {} + client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_revisions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_backup_plan_revisions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_backup_plan_revisions + ] = mock_rpc + + request = {} + await client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_backup_plan_revisions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlanRevisionsRequest(), + {}, + ], +) +async def test_list_backup_plan_revisions_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplan.ListBackupPlanRevisionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlanRevisionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_plan_revisions_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.ListBackupPlanRevisionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlanRevisionsResponse() + client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplan.ListBackupPlanRevisionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlanRevisionsResponse() + ) + await client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_backup_plan_revisions_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.ListBackupPlanRevisionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backup_plan_revisions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_backup_plan_revisions_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_plan_revisions( + backupplan.ListBackupPlanRevisionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplan.ListBackupPlanRevisionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlanRevisionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backup_plan_revisions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backup_plan_revisions( + backupplan.ListBackupPlanRevisionsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_revisions_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backup_plan_revisions( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupplan.BackupPlanRevision) for i in results) + + +def test_list_backup_plan_revisions_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backup_plan_revisions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backup_plan_revisions( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, backupplan.BackupPlanRevision) for i in responses) + + +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backup_plan_revisions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.CreateBackupPlanAssociationRequest(), + {}, + ], +) +def test_create_backup_plan_association(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.CreateBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_plan_association_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplanassociation.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_backup_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + ) + assert args[0] == request_msg + + +def test_create_backup_plan_association_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_backup_plan_association + ] = mock_rpc + request = {} + client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_backup_plan_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_backup_plan_association + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_backup_plan_association + ] = mock_rpc + + request = {} + await client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.CreateBackupPlanAssociationRequest(), + {}, + ], +) +async def test_create_backup_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplanassociation.CreateBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_plan_association_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.CreateBackupPlanAssociationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_backup_plan_association_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.CreateBackupPlanAssociationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_backup_plan_association_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_backup_plan_association( + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ) + assert arg == mock_val + arg = args[0].backup_plan_association_id + mock_val = "backup_plan_association_id_value" + assert arg == mock_val + + +def test_create_backup_plan_association_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_backup_plan_association( + backupplanassociation.CreateBackupPlanAssociationRequest(), + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_backup_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_backup_plan_association( + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ) + assert arg == mock_val + arg = args[0].backup_plan_association_id + mock_val = "backup_plan_association_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_backup_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_backup_plan_association( + backupplanassociation.CreateBackupPlanAssociationRequest(), + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.UpdateBackupPlanAssociationRequest(), + {}, + ], +) +def test_update_backup_plan_association(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.UpdateBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_plan_association_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplanassociation.UpdateBackupPlanAssociationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_backup_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + assert args[0] == request_msg + + +def test_update_backup_plan_association_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_backup_plan_association + ] = mock_rpc + request = {} + client.update_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_backup_plan_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_backup_plan_association + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_backup_plan_association + ] = mock_rpc + + request = {} + await client.update_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.UpdateBackupPlanAssociationRequest(), + {}, + ], +) +async def test_update_backup_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplanassociation.UpdateBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_backup_plan_association_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.UpdateBackupPlanAssociationRequest() + + request.backup_plan_association.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup_plan_association.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_backup_plan_association_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.UpdateBackupPlanAssociationRequest() + + request.backup_plan_association.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "backup_plan_association.name=name_value", + ) in kw["metadata"] + + +def test_update_backup_plan_association_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_backup_plan_association( + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_backup_plan_association_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup_plan_association( + backupplanassociation.UpdateBackupPlanAssociationRequest(), + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_backup_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_backup_plan_association( + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_backup_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_backup_plan_association( + backupplanassociation.UpdateBackupPlanAssociationRequest(), + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.GetBackupPlanAssociationRequest(), + {}, + ], +) +def test_get_backup_plan_association(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + response = client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.GetBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplanassociation.BackupPlanAssociation) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert response.resource == "resource_value" + assert response.backup_plan == "backup_plan_value" + assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING + assert response.data_source == "data_source_value" + assert response.backup_plan_revision_id == "backup_plan_revision_id_value" + assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) + + +def test_get_backup_plan_association_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplanassociation.GetBackupPlanAssociationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_backup_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_backup_plan_association_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_backup_plan_association + ] = mock_rpc + request = {} + client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_backup_plan_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_backup_plan_association + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_backup_plan_association + ] = mock_rpc + + request = {} + await client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.GetBackupPlanAssociationRequest(), + {}, + ], +) +async def test_get_backup_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + ) + response = await client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplanassociation.GetBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplanassociation.BackupPlanAssociation) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert response.resource == "resource_value" + assert response.backup_plan == "backup_plan_value" + assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING + assert response.data_source == "data_source_value" + assert response.backup_plan_revision_id == "backup_plan_revision_id_value" + assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) + + +def test_get_backup_plan_association_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.GetBackupPlanAssociationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + call.return_value = backupplanassociation.BackupPlanAssociation() + client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_backup_plan_association_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.GetBackupPlanAssociationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.BackupPlanAssociation() + ) + await client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_backup_plan_association_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplanassociation.BackupPlanAssociation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup_plan_association( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_backup_plan_association_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_plan_association( + backupplanassociation.GetBackupPlanAssociationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_backup_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplanassociation.BackupPlanAssociation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.BackupPlanAssociation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup_plan_association( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_backup_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup_plan_association( + backupplanassociation.GetBackupPlanAssociationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.ListBackupPlanAssociationsRequest(), + {}, + ], +) +def test_list_backup_plan_associations(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.ListBackupPlanAssociationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlanAssociationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_plan_associations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplanassociation.ListBackupPlanAssociationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_backup_plan_associations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + assert args[0] == request_msg + + +def test_list_backup_plan_associations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_backup_plan_associations + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_backup_plan_associations + ] = mock_rpc + request = {} + client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_associations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_backup_plan_associations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_backup_plan_associations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_backup_plan_associations + ] = mock_rpc + + request = {} + await client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_backup_plan_associations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.ListBackupPlanAssociationsRequest(), + {}, + ], +) +async def test_list_backup_plan_associations_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplanassociation.ListBackupPlanAssociationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlanAssociationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_backup_plan_associations_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.ListBackupPlanAssociationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_backup_plan_associations_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.ListBackupPlanAssociationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.ListBackupPlanAssociationsResponse() + ) + await client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_backup_plan_associations_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backup_plan_associations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_backup_plan_associations_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_plan_associations( + backupplanassociation.ListBackupPlanAssociationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_backup_plan_associations_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.ListBackupPlanAssociationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backup_plan_associations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_backup_plan_associations_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backup_plan_associations( + backupplanassociation.ListBackupPlanAssociationsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_associations_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backup_plan_associations( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results + ) + + +def test_list_backup_plan_associations_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backup_plan_associations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_backup_plan_associations_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backup_plan_associations( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, backupplanassociation.BackupPlanAssociation) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_backup_plan_associations_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_backup_plan_associations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + {}, + ], +) +def test_fetch_backup_plan_associations_for_resource_type( + request_type, transport: str = "grpc" +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchBackupPlanAssociationsForResourceTypePager) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_backup_plan_associations_for_resource_type_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_backup_plan_associations_for_resource_type(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + ) + assert args[0] == request_msg + + +def test_fetch_backup_plan_associations_for_resource_type_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_backup_plan_associations_for_resource_type + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_backup_plan_associations_for_resource_type + ] = mock_rpc + request = {} + client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.fetch_backup_plan_associations_for_resource_type + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.fetch_backup_plan_associations_for_resource_type + ] = mock_rpc + + request = {} + await client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + {}, + ], +) +async def test_fetch_backup_plan_associations_for_resource_type_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.fetch_backup_plan_associations_for_resource_type( + request + ) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager + ) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_backup_plan_associations_for_resource_type_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + await client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_fetch_backup_plan_associations_for_resource_type_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_backup_plan_associations_for_resource_type( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" + assert arg == mock_val + + +def test_fetch_backup_plan_associations_for_resource_type_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_backup_plan_associations_for_resource_type( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_backup_plan_associations_for_resource_type( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.fetch_backup_plan_associations_for_resource_type( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backup_plan_associations_for_resource_type_pager( + transport_name: str = "grpc", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.fetch_backup_plan_associations_for_resource_type( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results + ) + + +def test_fetch_backup_plan_associations_for_resource_type_pages( + transport_name: str = "grpc", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + pages = list( + client.fetch_backup_plan_associations_for_resource_type(request={}).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_backup_plan_associations_for_resource_type( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, backupplanassociation.BackupPlanAssociation) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.fetch_backup_plan_associations_for_resource_type(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.DeleteBackupPlanAssociationRequest(), + {}, + ], +) +def test_delete_backup_plan_association(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.DeleteBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_plan_association_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplanassociation.DeleteBackupPlanAssociationRequest( + name="name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_backup_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest( + name="name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + assert args[0] == request_msg + + +def test_delete_backup_plan_association_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_backup_plan_association + ] = mock_rpc + request = {} + client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_backup_plan_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_backup_plan_association + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_backup_plan_association + ] = mock_rpc + + request = {} + await client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.DeleteBackupPlanAssociationRequest(), + {}, + ], +) +async def test_delete_backup_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplanassociation.DeleteBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_plan_association_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.DeleteBackupPlanAssociationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_backup_plan_association_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.DeleteBackupPlanAssociationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_backup_plan_association_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup_plan_association( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_backup_plan_association_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup_plan_association( + backupplanassociation.DeleteBackupPlanAssociationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_backup_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup_plan_association( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_backup_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_backup_plan_association( + backupplanassociation.DeleteBackupPlanAssociationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.TriggerBackupRequest(), + {}, + ], +) +def test_trigger_backup(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.trigger_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.TriggerBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_trigger_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupplanassociation.TriggerBackupRequest( + name="name_value", + rule_id="rule_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.trigger_backup(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest( + name="name_value", + rule_id="rule_id_value", + ) + assert args[0] == request_msg + + +def test_trigger_backup_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.trigger_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.trigger_backup] = mock_rpc + request = {} + client.trigger_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.trigger_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_trigger_backup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.trigger_backup + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.trigger_backup + ] = mock_rpc + + request = {} + await client.trigger_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.trigger_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.TriggerBackupRequest(), + {}, + ], +) +async def test_trigger_backup_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.trigger_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupplanassociation.TriggerBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_trigger_backup_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.TriggerBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_trigger_backup_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupplanassociation.TriggerBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.trigger_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_trigger_backup_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.trigger_backup( + name="name_value", + rule_id="rule_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].rule_id + mock_val = "rule_id_value" + assert arg == mock_val + + +def test_trigger_backup_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.trigger_backup( + backupplanassociation.TriggerBackupRequest(), + name="name_value", + rule_id="rule_id_value", + ) + + +@pytest.mark.asyncio +async def test_trigger_backup_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.trigger_backup( + name="name_value", + rule_id="rule_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].rule_id + mock_val = "rule_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_trigger_backup_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.trigger_backup( + backupplanassociation.TriggerBackupRequest(), + name="name_value", + rule_id="rule_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.GetDataSourceReferenceRequest(), + {}, + ], +) +def test_get_data_source_reference(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, + ) + response = client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasourcereference.GetDataSourceReferenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasourcereference.DataSourceReference) + assert response.name == "name_value" + assert response.data_source == "data_source_value" + assert ( + response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE + ) + assert response.data_source_backup_count == 2535 + assert response.total_stored_bytes == 1946 + + +def test_get_data_source_reference_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = datasourcereference.GetDataSourceReferenceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_data_source_reference(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_data_source_reference_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_data_source_reference + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_data_source_reference + ] = mock_rpc + request = {} + client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source_reference(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_data_source_reference_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_data_source_reference + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_data_source_reference + ] = mock_rpc + + request = {} + await client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_data_source_reference(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.GetDataSourceReferenceRequest(), + {}, + ], +) +async def test_get_data_source_reference_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, + ) + ) + response = await client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasourcereference.GetDataSourceReferenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasourcereference.DataSourceReference) + assert response.name == "name_value" + assert response.data_source == "data_source_value" + assert ( + response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE + ) + assert response.data_source_backup_count == 2535 + assert response.total_stored_bytes == 1946 + + +def test_get_data_source_reference_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datasourcereference.GetDataSourceReferenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + call.return_value = datasourcereference.DataSourceReference() + client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_data_source_reference_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datasourcereference.GetDataSourceReferenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference() + ) + await client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_data_source_reference_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.DataSourceReference() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_source_reference( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_data_source_reference_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_source_reference( + datasourcereference.GetDataSourceReferenceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_data_source_reference_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.DataSourceReference() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_source_reference( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_data_source_reference_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_source_reference( + datasourcereference.GetDataSourceReferenceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.ListDataSourceReferencesRequest(), + {}, + ], +) +def test_list_data_source_references(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasourcereference.ListDataSourceReferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourceReferencesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_data_source_references_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = datasourcereference.ListDataSourceReferencesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_data_source_references(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_data_source_references_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_data_source_references + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_data_source_references + ] = mock_rpc + request = {} + client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_source_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_data_source_references_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_data_source_references + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_data_source_references + ] = mock_rpc + + request = {} + await client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_data_source_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.ListDataSourceReferencesRequest(), + {}, + ], +) +async def test_list_data_source_references_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasourcereference.ListDataSourceReferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourceReferencesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_data_source_references_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datasourcereference.ListDataSourceReferencesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_data_source_references_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datasourcereference.ListDataSourceReferencesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse() + ) + await client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_data_source_references_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_source_references( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_data_source_references_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_source_references( + datasourcereference.ListDataSourceReferencesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_data_source_references_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_source_references( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_data_source_references_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_data_source_references( + datasourcereference.ListDataSourceReferencesRequest(), + parent="parent_value", + ) + + +def test_list_data_source_references_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_data_source_references( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in results + ) + + +def test_list_data_source_references_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_source_references(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_data_source_references_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_source_references( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_data_source_references_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_data_source_references(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + {}, + ], +) +def test_fetch_data_source_references_for_resource_type( + request_type, transport: str = "grpc" +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDataSourceReferencesForResourceTypePager) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_data_source_references_for_resource_type_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_data_source_references_for_resource_type(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + ) + assert args[0] == request_msg + + +def test_fetch_data_source_references_for_resource_type_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_data_source_references_for_resource_type + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_data_source_references_for_resource_type + ] = mock_rpc + request = {} + client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_data_source_references_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.fetch_data_source_references_for_resource_type + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.fetch_data_source_references_for_resource_type + ] = mock_rpc + + request = {} + await client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_data_source_references_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + {}, + ], +) +async def test_fetch_data_source_references_for_resource_type_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, pagers.FetchDataSourceReferencesForResourceTypeAsyncPager + ) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_data_source_references_for_resource_type_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + await client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_fetch_data_source_references_for_resource_type_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_data_source_references_for_resource_type( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" + assert arg == mock_val + + +def test_fetch_data_source_references_for_resource_type_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_data_source_references_for_resource_type( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_data_source_references_for_resource_type( + parent="parent_value", + resource_type="resource_type_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.fetch_data_source_references_for_resource_type( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_data_source_references_for_resource_type_pager( + transport_name: str = "grpc", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.fetch_data_source_references_for_resource_type( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in results + ) + + +def test_fetch_data_source_references_for_resource_type_pages( + transport_name: str = "grpc", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + pages = list( + client.fetch_data_source_references_for_resource_type(request={}).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_data_source_references_for_resource_type( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in responses + ) + + +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.fetch_data_source_references_for_resource_type(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.InitializeServiceRequest(), + {}, + ], +) +def test_initialize_service(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupdr.InitializeServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_initialize_service_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupdr.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + backup_plan_location="backup_plan_location_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.initialize_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + backup_plan_location="backup_plan_location_value", + ) + assert args[0] == request_msg + + +def test_initialize_service_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.initialize_service in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.initialize_service] = ( + mock_rpc + ) + request = {} + client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.initialize_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_initialize_service_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.initialize_service + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.initialize_service + ] = mock_rpc + + request = {} + await client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.initialize_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + backupdr.InitializeServiceRequest(), + {}, + ], +) +async def test_initialize_service_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupdr.InitializeServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_initialize_service_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.InitializeServiceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_initialize_service_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.InitializeServiceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + {}, + ], +) +def test_create_auto_protection_policy(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_auto_protection_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + ) + assert args[0] == request_msg + + +def test_create_auto_protection_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_auto_protection_policy + ] = mock_rpc + request = {} + client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_auto_protection_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_auto_protection_policy + ] = mock_rpc + + request = {} + await client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_create_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_auto_protection_policy_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_auto_protection_policy( + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].auto_protection_policy_id + mock_val = "auto_protection_policy_id_value" + assert arg == mock_val + + +def test_create_auto_protection_policy_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_auto_protection_policy( + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].auto_protection_policy_id + mock_val = "auto_protection_policy_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + {}, + ], +) +def test_list_auto_protection_policies(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auto_protection_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_auto_protection_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_auto_protection_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_auto_protection_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policies + ] = mock_rpc + request = {} + client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_auto_protection_policies + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_auto_protection_policies + ] = mock_rpc + + request = {} + await client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_auto_protection_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + {}, + ], +) +async def test_list_auto_protection_policies_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auto_protection_policies_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_auto_protection_policies_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + ) + await client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_auto_protection_policies_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_auto_protection_policies( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_auto_protection_policies_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_auto_protection_policies_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_auto_protection_policies( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_auto_protection_policies_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policies_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_auto_protection_policies( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, autoprotectionpolicy.AutoProtectionPolicy) for i in results + ) + + +def test_list_auto_protection_policies_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_auto_protection_policies(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_auto_protection_policies( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, autoprotectionpolicy.AutoProtectionPolicy) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_auto_protection_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + {}, + ], +) +def test_get_auto_protection_policy(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) + response = client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING + assert response.etag == "etag_value" + + +def test_get_auto_protection_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_auto_protection_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_auto_protection_policy + ] = mock_rpc + request = {} + client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_auto_protection_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_auto_protection_policy + ] = mock_rpc + + request = {} + await client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_get_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) + ) + response = await client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING + assert response.etag == "etag_value" + + +def test_get_auto_protection_policy_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy() + ) + await client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_auto_protection_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_auto_protection_policy_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_auto_protection_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + {}, + ], +) +def test_update_auto_protection_policy(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_auto_protection_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +def test_update_auto_protection_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_auto_protection_policy + ] = mock_rpc + request = {} + client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_auto_protection_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_auto_protection_policy + ] = mock_rpc + + request = {} + await client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_update_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_auto_protection_policy_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + + request.auto_protection_policy.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "auto_protection_policy.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + + request.auto_protection_policy.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "auto_protection_policy.name=name_value", + ) in kw["metadata"] + + +def test_update_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_auto_protection_policy( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_auto_protection_policy_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_auto_protection_policy( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + {}, + ], +) +def test_delete_auto_protection_policy(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_auto_protection_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( + name="name_value", + etag="etag_value", + ) + assert args[0] == request_msg + + +def test_delete_auto_protection_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_auto_protection_policy + ] = mock_rpc + request = {} + client.delete_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_auto_protection_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_auto_protection_policy + ] = mock_rpc + + request = {} + await client.delete_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_delete_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_auto_protection_policy_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_auto_protection_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_auto_protection_policy_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_auto_protection_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_create_auto_protection_policy_binding(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_auto_protection_policy_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + assert args[0] == request_msg + + +def test_create_auto_protection_policy_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_auto_protection_policy_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_auto_protection_policy_binding + ] = mock_rpc + request = {} + client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_auto_protection_policy_binding + ] = mock_rpc + + request = {} + await client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + {}, + ], +) +async def test_create_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_auto_protection_policy_binding_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_auto_protection_policy_binding_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_auto_protection_policy_binding( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].auto_protection_policy_binding + mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ) + assert arg == mock_val + arg = args[0].auto_protection_policy_binding_id + mock_val = "auto_protection_policy_binding_id_value" + assert arg == mock_val + + +def test_create_auto_protection_policy_binding_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_auto_protection_policy_binding( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].auto_protection_policy_binding + mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ) + assert arg == mock_val + arg = args[0].auto_protection_policy_binding_id + mock_val = "auto_protection_policy_binding_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_get_auto_protection_policy_binding(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) + response = client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING + ) + assert response.scope == "scope_value" + assert response.etag == "etag_value" + + +def test_get_auto_protection_policy_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_auto_protection_policy_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_auto_protection_policy_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_auto_protection_policy_binding + ] = mock_rpc + request = {} + client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_auto_protection_policy_binding + ] = mock_rpc + + request = {} + await client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + {}, + ], +) +async def test_get_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) + ) + response = await client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING + ) + assert response.scope == "scope_value" + assert response.etag == "etag_value" + + +def test_get_auto_protection_policy_binding_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) + await client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_auto_protection_policy_binding_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_auto_protection_policy_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_auto_protection_policy_binding_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_auto_protection_policy_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + {}, + ], +) +def test_list_auto_protection_policy_bindings(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auto_protection_policy_bindings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_auto_protection_policy_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + ) + assert args[0] == request_msg + + +def test_list_auto_protection_policy_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_auto_protection_policy_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policy_bindings + ] = mock_rpc + request = {} + client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_policy_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_auto_protection_policy_bindings + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_auto_protection_policy_bindings + ] = mock_rpc + + request = {} + await client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_auto_protection_policy_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + {}, + ], +) +async def test_list_auto_protection_policy_bindings_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auto_protection_policy_bindings_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + await client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_auto_protection_policy_bindings_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_auto_protection_policy_bindings( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_auto_protection_policy_bindings_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_auto_protection_policy_bindings( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policy_bindings_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_auto_protection_policy_bindings( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in results + ) + + +def test_list_auto_protection_policy_bindings_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_auto_protection_policy_bindings(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_auto_protection_policy_bindings( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_auto_protection_policy_bindings(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + {}, + ], +) +def test_list_applied_auto_protection_policies(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_applied_auto_protection_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_applied_auto_protection_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + ) + assert args[0] == request_msg + + +def test_list_applied_auto_protection_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_applied_auto_protection_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_applied_auto_protection_policies + ] = mock_rpc + request = {} + client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applied_auto_protection_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_applied_auto_protection_policies + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_applied_auto_protection_policies + ] = mock_rpc + + request = {} + await client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_applied_auto_protection_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + {}, + ], +) +async def test_list_applied_auto_protection_policies_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_applied_auto_protection_policies_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + await client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_applied_auto_protection_policies_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_applied_auto_protection_policies( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_applied_auto_protection_policies_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_applied_auto_protection_policies( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_applied_auto_protection_policies_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_applied_auto_protection_policies( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in results + ) + + +def test_list_applied_auto_protection_policies_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_applied_auto_protection_policies(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_applied_auto_protection_policies( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_applied_auto_protection_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_initiate_delete_auto_protection_policy_binding( + request_type, transport: str = "grpc" +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_initiate_delete_auto_protection_policy_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.initiate_delete_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_initiate_delete_auto_protection_policy_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.initiate_delete_auto_protection_policy_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.initiate_delete_auto_protection_policy_binding + ] = mock_rpc + request = {} + client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.initiate_delete_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.initiate_delete_auto_protection_policy_binding + ] = mock_rpc + + request = {} + await client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + {}, + ], +) +async def test_initiate_delete_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_initiate_delete_auto_protection_policy_binding_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + ) + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + ) + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_initiate_delete_auto_protection_policy_binding_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.initiate_delete_auto_protection_policy_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_initiate_delete_auto_protection_policy_binding_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.initiate_delete_auto_protection_policy_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.GetBindingMatchingResourceRequest(), + {}, + ], +) +def test_get_binding_matching_resource(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bindingmatchingresource.BindingMatchingResource( + name="name_value", + resource="resource_value", + ) + response = client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.GetBindingMatchingResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bindingmatchingresource.BindingMatchingResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + + +def test_get_binding_matching_resource_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bindingmatchingresource.GetBindingMatchingResourceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_binding_matching_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_binding_matching_resource_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_binding_matching_resource + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_binding_matching_resource + ] = mock_rpc + request = {} + client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_binding_matching_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_binding_matching_resource_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_binding_matching_resource + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_binding_matching_resource + ] = mock_rpc + + request = {} + await client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_binding_matching_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.GetBindingMatchingResourceRequest(), + {}, + ], +) +async def test_get_binding_matching_resource_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource( + name="name_value", + resource="resource_value", + ) + ) + response = await client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.GetBindingMatchingResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bindingmatchingresource.BindingMatchingResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + + +def test_get_binding_matching_resource_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bindingmatchingresource.GetBindingMatchingResourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + call.return_value = bindingmatchingresource.BindingMatchingResource() + client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_binding_matching_resource_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bindingmatchingresource.GetBindingMatchingResourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource() + ) + await client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_binding_matching_resource_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bindingmatchingresource.BindingMatchingResource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_binding_matching_resource( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_binding_matching_resource_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_binding_matching_resource( + bindingmatchingresource.GetBindingMatchingResourceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_binding_matching_resource_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bindingmatchingresource.BindingMatchingResource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_binding_matching_resource( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_binding_matching_resource_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_binding_matching_resource( + bindingmatchingresource.GetBindingMatchingResourceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + {}, + ], +) +def test_list_binding_matching_resources(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBindingMatchingResourcesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_binding_matching_resources_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bindingmatchingresource.ListBindingMatchingResourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_binding_matching_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_binding_matching_resources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_binding_matching_resources + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_binding_matching_resources + ] = mock_rpc + request = {} + client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_binding_matching_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_binding_matching_resources + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_binding_matching_resources + ] = mock_rpc + + request = {} + await client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_binding_matching_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + {}, + ], +) +async def test_list_binding_matching_resources_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBindingMatchingResourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_binding_matching_resources_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_binding_matching_resources_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + await client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_binding_matching_resources_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_binding_matching_resources( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_binding_matching_resources_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_binding_matching_resources_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_binding_matching_resources( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_binding_matching_resources_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + parent="parent_value", + ) + + +def test_list_binding_matching_resources_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_binding_matching_resources( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, bindingmatchingresource.BindingMatchingResource) + for i in results + ) + + +def test_list_binding_matching_resources_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_binding_matching_resources(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_binding_matching_resources( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, bindingmatchingresource.BindingMatchingResource) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_binding_matching_resources(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_management_servers_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_management_servers + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_management_servers + ] = mock_rpc + + request = {} + client.list_management_servers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_management_servers(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_management_servers_rest_required_fields( + request_type=backupdr.ListManagementServersRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListManagementServers, + "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupdr.ListManagementServersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupdr.ListManagementServersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_management_servers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_management_servers_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupdr.ListManagementServersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupdr.ListManagementServersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_management_servers(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/managementServers" + % client.transport._host, + args[1], + ) + + +def test_list_management_servers_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_management_servers( + backupdr.ListManagementServersRequest(), + parent="parent_value", + ) + + +def test_list_management_servers_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + next_page_token="abc", + ), + backupdr.ListManagementServersResponse( + management_servers=[], + next_page_token="def", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + ], + next_page_token="ghi", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupdr.ListManagementServersResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_management_servers(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupdr.ManagementServer) for i in results) + + pages = list(client.list_management_servers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_management_server_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_management_server + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_management_server] = ( + mock_rpc + ) + + request = {} + client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_management_server_rest_required_fields( + request_type=backupdr.GetManagementServerRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetManagementServer, + "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupdr.ManagementServer() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupdr.ManagementServer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_management_server(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_management_server_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupdr.ManagementServer() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupdr.ManagementServer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_management_server(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/managementServers/*}" + % client.transport._host, + args[1], + ) + + +def test_get_management_server_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_management_server( + backupdr.GetManagementServerRequest(), + name="name_value", + ) + + +def test_create_management_server_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_management_server + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_management_server + ] = mock_rpc + + request = {} + client.create_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_management_server_rest_required_fields( + request_type=backupdr.CreateManagementServerRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["management_server_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "managementServerId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateManagementServer, + "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "managementServerId" in jsonified_request + assert ( + jsonified_request["managementServerId"] == request_init["management_server_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["managementServerId"] = "management_server_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "managementServerId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "managementServerId" in jsonified_request + assert jsonified_request["managementServerId"] == "management_server_id_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_management_server(request) + + expected_params = [ + ( + "managementServerId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_management_server_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_management_server(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/managementServers" + % client.transport._host, + args[1], + ) + + +def test_create_management_server_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_management_server( + backupdr.CreateManagementServerRequest(), + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", + ) + + +def test_delete_management_server_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_management_server + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_management_server + ] = mock_rpc + + request = {} + client.delete_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_management_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_management_server_rest_required_fields( + request_type=backupdr.DeleteManagementServerRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteManagementServer, + "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_management_server(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_management_server_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_management_server(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/managementServers/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_management_server_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_management_server( + backupdr.DeleteManagementServerRequest(), + name="name_value", + ) + + +def test_create_backup_vault_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_backup_vault in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_backup_vault] = ( + mock_rpc + ) + + request = {} + client.create_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_backup_vault_rest_required_fields( + request_type=backupvault.CreateBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_vault_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "backupVaultId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupVault, + "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupVaultId" in jsonified_request + assert jsonified_request["backupVaultId"] == request_init["backup_vault_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupVaultId"] = "backup_vault_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupVaultId", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupVaultId" in jsonified_request + assert jsonified_request["backupVaultId"] == "backup_vault_id_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_backup_vault(request) + + expected_params = [ + ( + "backupVaultId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_vault_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_backup_vault(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupVaults" + % client.transport._host, + args[1], + ) + + +def test_create_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_backup_vault( + backupvault.CreateBackupVaultRequest(), + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + + +def test_list_backup_vaults_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_backup_vaults in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_backup_vaults] = ( + mock_rpc + ) + + request = {} + client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_vaults(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_backup_vaults_rest_required_fields( + request_type=backupvault.ListBackupVaultsRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListBackupVaults, + "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupVaultsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_backup_vaults(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_backup_vaults_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupVaultsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_backup_vaults(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupVaults" + % client.transport._host, + args[1], + ) + + +def test_list_backup_vaults_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_vaults( + backupvault.ListBackupVaultsRequest(), + parent="parent_value", + ) + + +def test_list_backup_vaults_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.ListBackupVaultsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_backup_vaults(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in results) + + pages = list(client.list_backup_vaults(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_usable_backup_vaults_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_usable_backup_vaults + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_usable_backup_vaults + ] = mock_rpc + + request = {} + client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_usable_backup_vaults(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_usable_backup_vaults_rest_required_fields( + request_type=backupvault.FetchUsableBackupVaultsRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseFetchUsableBackupVaults, + "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchUsableBackupVaultsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.fetch_usable_backup_vaults(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_usable_backup_vaults_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchUsableBackupVaultsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.fetch_usable_backup_vaults(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupVaults:fetchUsable" + % client.transport._host, + args[1], + ) + + +def test_fetch_usable_backup_vaults_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_usable_backup_vaults( + backupvault.FetchUsableBackupVaultsRequest(), + parent="parent_value", + ) + + +def test_fetch_usable_backup_vaults_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.FetchUsableBackupVaultsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.fetch_usable_backup_vaults(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in results) + + pages = list(client.fetch_usable_backup_vaults(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_backup_vault_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_backup_vault in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_backup_vault] = ( + mock_rpc + ) + + request = {} + client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_backup_vault_rest_required_fields( + request_type=backupvault.GetBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetBackupVault, + "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.BackupVault() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_backup_vault(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_backup_vault_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.BackupVault() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_backup_vault(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_vault( + backupvault.GetBackupVaultRequest(), + name="name_value", + ) + + +def test_update_backup_vault_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_backup_vault in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_backup_vault] = ( + mock_rpc + ) + + request = {} + client.update_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_backup_vault_rest_required_fields( + request_type=backupvault.UpdateBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateBackupVault, + "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "forceUpdateAccessRestriction", + "requestId", + "updateMask", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_backup_vault(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_backup_vault_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "backup_vault": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_backup_vault(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{backup_vault.name=projects/*/locations/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup_vault( + backupvault.UpdateBackupVaultRequest(), + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_backup_vault_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_backup_vault in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_backup_vault] = ( + mock_rpc + ) + + request = {} + client.delete_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup_vault(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_backup_vault_rest_required_fields( + request_type=backupvault.DeleteBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteBackupVault, + "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "etag", + "force", + "ignoreBackupPlanReferences", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_backup_vault(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_backup_vault_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_backup_vault(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup_vault( + backupvault.DeleteBackupVaultRequest(), + name="name_value", + ) + + +def test_list_data_sources_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_sources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_data_sources] = ( + mock_rpc + ) + + request = {} + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_sources_rest_required_fields( + request_type=backupvault.ListDataSourcesRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListDataSources, + "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.ListDataSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_data_sources(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_data_sources_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.ListDataSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_data_sources(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/backupVaults/*}/dataSources" + % client.transport._host, + args[1], + ) + + +def test_list_data_sources_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_sources( + backupvault.ListDataSourcesRequest(), + parent="parent_value", + ) + + +def test_list_data_sources_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.ListDataSourcesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3" + } + + pager = client.list_data_sources(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.DataSource) for i in results) + + pages = list(client.list_data_sources(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_data_source_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_source in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_data_source] = mock_rpc + + request = {} + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_source_rest_required_fields( + request_type=backupvault.GetDataSourceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetDataSource, + "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.DataSource() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_data_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_data_source_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.DataSource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_data_source(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_data_source_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_source( + backupvault.GetDataSourceRequest(), + name="name_value", + ) + + +def test_update_data_source_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_data_source in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_data_source] = ( + mock_rpc + ) + + request = {} + client.update_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_data_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_source_rest_required_fields( + request_type=backupvault.UpdateDataSourceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateDataSource, + "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_data_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_data_source_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "data_source": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_data_source(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{data_source.name=projects/*/locations/*/backupVaults/*/dataSources/*}" + % client.transport._host, + args[1], + ) + + +def test_update_data_source_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_source( + backupvault.UpdateDataSourceRequest(), + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_list_backups_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_backups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc + + request = {} + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_backups_rest_required_fields(request_type=backupvault.ListBackupsRequest): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListBackups, + "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_backups(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_backups_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_backups(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups" + % client.transport._host, + args[1], + ) + + +def test_list_backups_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backups( + backupvault.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(backupvault.ListBackupsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + + pager = client.list_backups(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.Backup) for i in results) + + pages = list(client.list_backups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_backups_for_resource_type_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_backups_for_resource_type + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_backups_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backups_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_backups_for_resource_type_rest_required_fields( + request_type=backupvault.FetchBackupsForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchBackupsForResourceType, + "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchBackupsForResourceTypeResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.FetchBackupsForResourceTypeResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.fetch_backups_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_backups_for_resource_type_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchBackupsForResourceTypeResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource_type="resource_type_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.fetch_backups_for_resource_type(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_backups_for_resource_type_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_backups_for_resource_type( + backupvault.FetchBackupsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backups_for_resource_type_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], + next_page_token="def", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.FetchBackupsForResourceTypeResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + + pager = client.fetch_backups_for_resource_type(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.Backup) for i in results) + + pages = list( + client.fetch_backups_for_resource_type(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_backup_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_backup] = mock_rpc + + request = {} + client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_backup_rest_required_fields(request_type=backupvault.GetBackupRequest): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetBackup, + "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.Backup() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_backup_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup( + backupvault.GetBackupRequest(), + name="name_value", + ) + + +def test_update_backup_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_backup] = mock_rpc + + request = {} + client.update_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_backup_rest_required_fields( + request_type=backupvault.UpdateBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateBackup, + "_BaseUpdateBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_backup_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "backup": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{backup.name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup( + backupvault.UpdateBackupRequest(), + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_backup_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_backup] = mock_rpc + + request = {} + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_backup_rest_required_fields( + request_type=backupvault.DeleteBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteBackup, + "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_backup_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup( + backupvault.DeleteBackupRequest(), + name="name_value", + ) + + +def test_restore_backup_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.restore_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.restore_backup] = mock_rpc + + request = {} + client.restore_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.restore_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_restore_backup_rest_required_fields( + request_type=backupvault.RestoreBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseRestoreBackup, + "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.restore_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_restore_backup_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.restore_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_backup( + backupvault.RestoreBackupRequest(), + name="name_value", + ) + + +def test_create_backup_plan_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_backup_plan in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_backup_plan] = ( + mock_rpc + ) + + request = {} + client.create_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_backup_plan_rest_required_fields( + request_type=backupplan.CreateBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_plan_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "backupPlanId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupPlan, + "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupPlanId" in jsonified_request + assert jsonified_request["backupPlanId"] == request_init["backup_plan_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupPlanId"] = "backup_plan_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupPlanId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupPlanId" in jsonified_request + assert jsonified_request["backupPlanId"] == "backup_plan_id_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_backup_plan(request) + + expected_params = [ + ( + "backupPlanId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_plan_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_backup_plan(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupPlans" + % client.transport._host, + args[1], + ) + + +def test_create_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_backup_plan( + backupplan.CreateBackupPlanRequest(), + parent="parent_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", + ) + + +def test_update_backup_plan_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_backup_plan in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_backup_plan] = ( + mock_rpc + ) + + request = {} + client.update_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_backup_plan_rest_required_fields( + request_type=backupplan.UpdateBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateBackupPlan, + "_BaseUpdateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_backup_plan(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_backup_plan_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "backup_plan": { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_backup_plan(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{backup_plan.name=projects/*/locations/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup_plan( + backupplan.UpdateBackupPlanRequest(), + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_backup_plan_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_backup_plan in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_backup_plan] = mock_rpc + + request = {} + client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_backup_plan_rest_required_fields( + request_type=backupplan.GetBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetBackupPlan, + "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlan() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_backup_plan(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_backup_plan_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlan() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_backup_plan(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_plan( + backupplan.GetBackupPlanRequest(), + name="name_value", + ) + + +def test_list_backup_plans_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_backup_plans in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_backup_plans] = ( + mock_rpc + ) + + request = {} + client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plans(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_backup_plans_rest_required_fields( + request_type=backupplan.ListBackupPlansRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListBackupPlans, + "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlansResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_backup_plans(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_backup_plans_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlansResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_backup_plans(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupPlans" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plans_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_plans( + backupplan.ListBackupPlansRequest(), + parent="parent_value", + ) + + +def test_list_backup_plans_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[], + next_page_token="def", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplan.ListBackupPlansResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_backup_plans(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupplan.BackupPlan) for i in results) + + pages = list(client.list_backup_plans(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_backup_plan_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_backup_plan in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_backup_plan] = ( + mock_rpc + ) + + request = {} + client.delete_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup_plan(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_backup_plan_rest_required_fields( + request_type=backupplan.DeleteBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteBackupPlan, + "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_backup_plan(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_backup_plan_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_backup_plan(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup_plan( + backupplan.DeleteBackupPlanRequest(), + name="name_value", + ) + + +def test_get_backup_plan_revision_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_backup_plan_revision + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_backup_plan_revision + ] = mock_rpc + + request = {} + client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_revision(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_backup_plan_revision_rest_required_fields( + request_type=backupplan.GetBackupPlanRevisionRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetBackupPlanRevision, + "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlanRevision() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_backup_plan_revision(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_backup_plan_revision_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlanRevision() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_backup_plan_revision(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupPlans/*/revisions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_revision_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_plan_revision( + backupplan.GetBackupPlanRevisionRequest(), + name="name_value", + ) + + +def test_list_backup_plan_revisions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_backup_plan_revisions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_backup_plan_revisions + ] = mock_rpc + + request = {} + client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_revisions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_backup_plan_revisions_rest_required_fields( + request_type=backupplan.ListBackupPlanRevisionsRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListBackupPlanRevisions, + "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlanRevisionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_backup_plan_revisions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_backup_plan_revisions_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlanRevisionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupPlans/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_backup_plan_revisions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/backupPlans/*}/revisions" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plan_revisions_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_plan_revisions( + backupplan.ListBackupPlanRevisionsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_revisions_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplan.ListBackupPlanRevisionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/backupPlans/sample3" + } + + pager = client.list_backup_plan_revisions(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupplan.BackupPlanRevision) for i in results) + + pages = list(client.list_backup_plan_revisions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_backup_plan_association_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_backup_plan_association + ] = mock_rpc + + request = {} + client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_plan_association_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "backupPlanAssociationId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupPlanAssociation, + "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupPlanAssociationId" in jsonified_request + assert ( + jsonified_request["backupPlanAssociationId"] + == request_init["backup_plan_association_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupPlanAssociationId"] = "backup_plan_association_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupPlanAssociationId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupPlanAssociationId" in jsonified_request + assert ( + jsonified_request["backupPlanAssociationId"] + == "backup_plan_association_id_value" + ) + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_backup_plan_association(request) + + expected_params = [ + ( + "backupPlanAssociationId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_plan_association_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_backup_plan_association(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupPlanAssociations" + % client.transport._host, + args[1], + ) + + +def test_create_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_backup_plan_association( + backupplanassociation.CreateBackupPlanAssociationRequest(), + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + + +def test_update_backup_plan_association_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_backup_plan_association + ] = mock_rpc + + request = {} + client.update_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateBackupPlanAssociation, + "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_backup_plan_association(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_backup_plan_association_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "backup_plan_association": { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_backup_plan_association(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{backup_plan_association.name=projects/*/locations/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup_plan_association( + backupplanassociation.UpdateBackupPlanAssociationRequest(), + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_backup_plan_association_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_backup_plan_association + ] = mock_rpc + + request = {} + client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.GetBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetBackupPlanAssociation, + "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.BackupPlanAssociation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplanassociation.BackupPlanAssociation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_backup_plan_association(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_backup_plan_association_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.BackupPlanAssociation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupplanassociation.BackupPlanAssociation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_backup_plan_association(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_plan_association( + backupplanassociation.GetBackupPlanAssociationRequest(), + name="name_value", + ) + + +def test_list_backup_plan_associations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_backup_plan_associations + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_backup_plan_associations + ] = mock_rpc + + request = {} + client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_associations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_backup_plan_associations_rest_required_fields( + request_type=backupplanassociation.ListBackupPlanAssociationsRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListBackupPlanAssociations, + "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_backup_plan_associations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_backup_plan_associations_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_backup_plan_associations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupPlanAssociations" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plan_associations_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_plan_associations( + backupplanassociation.ListBackupPlanAssociationsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_associations_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplanassociation.ListBackupPlanAssociationsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_backup_plan_associations(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results + ) + + pages = list(client.list_backup_plan_associations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_backup_plan_associations_for_resource_type_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_backup_plan_associations_for_resource_type + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_backup_plan_associations_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_backup_plan_associations_for_resource_type_rest_required_fields( + request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchBackupPlanAssociationsForResourceType, + "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.fetch_backup_plan_associations_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource_type="resource_type_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.fetch_backup_plan_associations_for_resource_type(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/backupPlanAssociations:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_backup_plan_associations_for_resource_type( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_pager( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( + x + ) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.fetch_backup_plan_associations_for_resource_type( + request=sample_request + ) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results + ) + + pages = list( + client.fetch_backup_plan_associations_for_resource_type( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_backup_plan_association_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_backup_plan_association + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_backup_plan_association + ] = mock_rpc + + request = {} + client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup_plan_association(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteBackupPlanAssociation, + "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "autoProtectionPolicyBinding", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_backup_plan_association(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_backup_plan_association_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_backup_plan_association(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup_plan_association( + backupplanassociation.DeleteBackupPlanAssociationRequest(), + name="name_value", + ) + + +def test_trigger_backup_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.trigger_backup in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.trigger_backup] = mock_rpc + + request = {} + client.trigger_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.trigger_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_trigger_backup_rest_required_fields( + request_type=backupplanassociation.TriggerBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseTriggerBackup, + "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.trigger_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_trigger_backup_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + rule_id="rule_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.trigger_backup(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/backupPlanAssociations/*}:triggerBackup" + % client.transport._host, + args[1], + ) + + +def test_trigger_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.trigger_backup( + backupplanassociation.TriggerBackupRequest(), + name="name_value", + rule_id="rule_id_value", + ) + + +def test_get_data_source_reference_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_data_source_reference + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_data_source_reference + ] = mock_rpc + + request = {} + client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source_reference(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_source_reference_rest_required_fields( + request_type=datasourcereference.GetDataSourceReferenceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetDataSourceReference, + "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasourcereference.DataSourceReference() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = datasourcereference.DataSourceReference.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_data_source_reference(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_data_source_reference_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = datasourcereference.DataSourceReference() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dataSourceReferences/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = datasourcereference.DataSourceReference.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_data_source_reference(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/dataSourceReferences/*}" + % client.transport._host, + args[1], + ) + + +def test_get_data_source_reference_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_source_reference( + datasourcereference.GetDataSourceReferenceRequest(), + name="name_value", + ) + + +def test_list_data_source_references_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_data_source_references + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_data_source_references + ] = mock_rpc + + request = {} + client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_source_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_source_references_rest_required_fields( + request_type=datasourcereference.ListDataSourceReferencesRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListDataSourceReferences, + "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasourcereference.ListDataSourceReferencesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_data_source_references(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_data_source_references_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = datasourcereference.ListDataSourceReferencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_data_source_references(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/dataSourceReferences" + % client.transport._host, + args[1], + ) + + +def test_list_data_source_references_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_source_references( + datasourcereference.ListDataSourceReferencesRequest(), + parent="parent_value", + ) + + +def test_list_data_source_references_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + datasourcereference.ListDataSourceReferencesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_data_source_references(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in results + ) + + pages = list(client.list_data_source_references(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_data_source_references_for_resource_type_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.fetch_data_source_references_for_resource_type + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_data_source_references_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_data_source_references_for_resource_type(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_data_source_references_for_resource_type_rest_required_fields( + request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchDataSourceReferencesForResourceType, + "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.fetch_data_source_references_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_data_source_references_for_resource_type_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource_type="resource_type_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.fetch_data_source_references_for_resource_type(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/dataSourceReferences:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_data_source_references_for_resource_type_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_data_source_references_for_resource_type( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_data_source_references_for_resource_type_rest_pager( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( + x + ) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.fetch_data_source_references_for_resource_type( + request=sample_request + ) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in results + ) + + pages = list( + client.fetch_data_source_references_for_resource_type( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_initialize_service_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.initialize_service in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.initialize_service] = ( + mock_rpc + ) + + request = {} + client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.initialize_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_initialize_service_rest_required_fields( + request_type=backupdr.InitializeServiceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request_init["resource_type"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseInitializeService, + "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["resourceType"] = "resource_type_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.initialize_service(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_auto_protection_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_auto_protection_policy + ] = mock_rpc + + request = {} + client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.CreateAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["auto_protection_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "autoProtectionPolicyId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateAutoProtectionPolicy, + "_BaseCreateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "autoProtectionPolicyId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyId"] + == request_init["auto_protection_policy_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["autoProtectionPolicyId"] = "auto_protection_policy_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("autoProtectionPolicyId",)) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "autoProtectionPolicyId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyId"] == "auto_protection_policy_id_value" + ) + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_auto_protection_policy(request) + + expected_params = [ + ( + "autoProtectionPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_auto_protection_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/autoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + +def test_list_auto_protection_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_auto_protection_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policies + ] = mock_rpc + + request = {} + client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_auto_protection_policies_rest_required_fields( + request_type=autoprotectionpolicy.ListAutoProtectionPoliciesRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAutoProtectionPolicies, + "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_auto_protection_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_auto_protection_policies_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_auto_protection_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/autoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_auto_protection_policies_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policies_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_auto_protection_policies(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, autoprotectionpolicy.AutoProtectionPolicy) for i in results + ) + + pages = list(client.list_auto_protection_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_auto_protection_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_auto_protection_policy + ] = mock_rpc + + request = {} + client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.GetAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetAutoProtectionPolicy, + "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.AutoProtectionPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_auto_protection_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.AutoProtectionPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_auto_protection_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", + ) + + +def test_update_auto_protection_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_auto_protection_policy + ] = mock_rpc + + request = {} + client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateAutoProtectionPolicy, + "_BaseUpdateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_auto_protection_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "auto_protection_policy": { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_auto_protection_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{auto_protection_policy.name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_auto_protection_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_auto_protection_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_auto_protection_policy + ] = mock_rpc + + request = {} + client.delete_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_auto_protection_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteAutoProtectionPolicy, + "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_auto_protection_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_auto_protection_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", + ) + + +def test_create_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_auto_protection_policy_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["auto_protection_policy_binding_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "autoProtectionPolicyBindingId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateAutoProtectionPolicyBinding, + "_BaseCreateAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "autoProtectionPolicyBindingId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyBindingId"] + == request_init["auto_protection_policy_binding_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["autoProtectionPolicyBindingId"] = ( + "auto_protection_policy_binding_id_value" + ) + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("autoProtectionPolicyBindingId",)) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "autoProtectionPolicyBindingId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyBindingId"] + == "auto_protection_policy_binding_id_value" + ) + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_auto_protection_policy_binding(request) + + expected_params = [ + ( + "autoProtectionPolicyBindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_auto_protection_policy_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/autoProtectionPolicies/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_create_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + +def test_get_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_auto_protection_policy_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetAutoProtectionPolicyBinding, + "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_auto_protection_policy_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_auto_protection_policy_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +def test_list_auto_protection_policy_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_auto_protection_policy_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policy_bindings + ] = mock_rpc + + request = {} + client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_policy_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_auto_protection_policy_bindings_rest_required_fields( + request_type=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAutoProtectionPolicyBindings, + "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_auto_protection_policy_bindings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_auto_protection_policy_bindings_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_auto_protection_policy_bindings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/autoProtectionPolicies/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_list_auto_protection_policy_bindings_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.to_json( + x + ) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + + pager = client.list_auto_protection_policy_bindings(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in results + ) + + pages = list( + client.list_auto_protection_policy_bindings(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_applied_auto_protection_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_applied_auto_protection_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_applied_auto_protection_policies + ] = mock_rpc + + request = {} + client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applied_auto_protection_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_applied_auto_protection_policies_rest_required_fields( + request_type=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAppliedAutoProtectionPolicies, + "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_applied_auto_protection_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_applied_auto_protection_policies_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_applied_auto_protection_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/appliedAutoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_applied_auto_protection_policies_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_applied_auto_protection_policies_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.to_json( + x + ) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_applied_auto_protection_policies(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in results + ) + + pages = list( + client.list_applied_auto_protection_policies(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_initiate_delete_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.initiate_delete_auto_protection_policy_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.initiate_delete_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_initiate_delete_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseInitiateDeleteAutoProtectionPolicyBinding, + "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.initiate_delete_auto_protection_policy_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_initiate_delete_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.initiate_delete_auto_protection_policy_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}:initiateDelete" + % client.transport._host, + args[1], + ) + + +def test_initiate_delete_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +def test_get_binding_matching_resource_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_binding_matching_resource + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_binding_matching_resource + ] = mock_rpc + + request = {} + client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_binding_matching_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_binding_matching_resource_rest_required_fields( + request_type=bindingmatchingresource.GetBindingMatchingResourceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetBindingMatchingResource, + "_BaseGetBindingMatchingResource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.BindingMatchingResource() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bindingmatchingresource.BindingMatchingResource.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_binding_matching_resource(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_binding_matching_resource_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.BindingMatchingResource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4/matchingResources/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bindingmatchingresource.BindingMatchingResource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_binding_matching_resource(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*/matchingResources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_binding_matching_resource_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_binding_matching_resource( + bindingmatchingresource.GetBindingMatchingResourceRequest(), + name="name_value", + ) + + +def test_list_binding_matching_resources_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_binding_matching_resources + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_binding_matching_resources + ] = mock_rpc + + request = {} + client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_binding_matching_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_binding_matching_resources_rest_required_fields( + request_type=bindingmatchingresource.ListBindingMatchingResourcesRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListBindingMatchingResources, + "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_binding_matching_resources(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_binding_matching_resources_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_binding_matching_resources(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}/matchingResources" + % client.transport._host, + args[1], + ) + + +def test_list_binding_matching_resources_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + parent="parent_value", + ) + + +def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bindingmatchingresource.ListBindingMatchingResourcesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + + pager = client.list_binding_matching_resources(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, bindingmatchingresource.BindingMatchingResource) + for i in results + ) + + pages = list( + client.list_binding_matching_resources(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BackupDRClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BackupDRClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BackupDRClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BackupDRGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDRGrpcTransport, + transports.BackupDRGrpcAsyncIOTransport, + transports.BackupDRRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = BackupDRClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_management_servers_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + call.return_value = backupdr.ListManagementServersResponse() + client.list_management_servers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + call.return_value = backupdr.ManagementServer() + client.get_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_vaults_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.ListBackupVaultsResponse() + client.list_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_usable_backup_vaults_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.FetchUsableBackupVaultsResponse() + client.fetch_usable_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + call.return_value = backupvault.BackupVault() + client.get_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_data_sources_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + call.return_value = backupvault.ListDataSourcesResponse() + client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_data_source_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + call.return_value = backupvault.DataSource() + client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_data_source_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backups_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = backupvault.ListBackupsResponse() + client.list_backups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_backups_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + client.fetch_backups_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = backupvault.Backup() + client.get_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + call.return_value = backupplan.BackupPlan() + client.get_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_plans_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlansResponse() + client.list_backup_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_plan_revision_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + call.return_value = backupplan.BackupPlanRevision() + client.get_backup_plan_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_plan_revisions_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlanRevisionsResponse() + client.list_backup_plan_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + call.return_value = backupplanassociation.BackupPlanAssociation() + client.get_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_plan_associations_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + client.list_backup_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_backup_plan_associations_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + client.fetch_backup_plan_associations_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_trigger_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_data_source_reference_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + call.return_value = datasourcereference.DataSourceReference() + client.get_data_source_reference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_data_source_references_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + client.list_data_source_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_data_source_references_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + client.fetch_data_source_references_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_initialize_service_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_auto_protection_policies_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_auto_protection_policy_bindings_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_applied_auto_protection_policies_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_initiate_delete_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_binding_matching_resource_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + call.return_value = bindingmatchingresource.BindingMatchingResource() + client.get_binding_matching_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_binding_matching_resources_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BackupDRAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_management_servers_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ListManagementServersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_management_servers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=True, + ) + ) + await client.get_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_backup_vaults_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_usable_backup_vaults_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchUsableBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.fetch_usable_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + ) + await client.get_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_data_sources_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_data_source_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) + ) + await client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_data_source_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_backups_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_backups_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_backups_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_value"], + ) + ) + await client.get_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_restore_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.restore_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlan( + name="name_value", + description="description_value", + max_custom_on_demand_retention_days=3723, + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) + ) + await client.get_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_backup_plans_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_backup_plan_revision_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + ) + await client.get_backup_plan_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plan_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + ) + await client.get_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_backup_plan_associations_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_backup_plan_associations_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_trigger_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.trigger_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_data_source_reference_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, + ) + ) + await client.get_data_source_reference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_data_source_references_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_data_source_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_data_source_references_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_initialize_service_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_auto_protection_policies_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) + ) + await client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) + ) + await client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_binding_matching_resource_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource( + name="name_value", + resource="resource_value", + ) + ) + await client.get_binding_matching_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_binding_matching_resources_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BackupDRClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_management_servers_rest_bad_request( + request_type=backupdr.ListManagementServersRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_management_servers(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.ListManagementServersRequest, + dict, + ], +) +def test_list_management_servers_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupdr.ListManagementServersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupdr.ListManagementServersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_management_servers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListManagementServersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_management_servers_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_management_servers" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_management_servers_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_management_servers" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.ListManagementServersRequest.pb( + backupdr.ListManagementServersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupdr.ListManagementServersResponse.to_json( + backupdr.ListManagementServersResponse() + ) + req.return_value.content = return_value + + request = backupdr.ListManagementServersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupdr.ListManagementServersResponse() + post_with_metadata.return_value = ( + backupdr.ListManagementServersResponse(), + metadata, + ) + + client.list_management_servers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_management_server_rest_bad_request( + request_type=backupdr.GetManagementServerRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.GetManagementServerRequest, + dict, + ], +) +def test_get_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupdr.ManagementServer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_management_server(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupdr.ManagementServer) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.type_ == backupdr.ManagementServer.InstanceType.BACKUP_RESTORE + assert response.state == backupdr.ManagementServer.InstanceState.CREATING + assert response.etag == "etag_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.ba_proxy_uri == ["ba_proxy_uri_value"] + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.GetManagementServerRequest.pb( + backupdr.GetManagementServerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupdr.ManagementServer.to_json(backupdr.ManagementServer()) + req.return_value.content = return_value + + request = backupdr.GetManagementServerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupdr.ManagementServer() + post_with_metadata.return_value = backupdr.ManagementServer(), metadata + + client.get_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_management_server_rest_bad_request( + request_type=backupdr.CreateManagementServerRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.CreateManagementServerRequest, + dict, + ], +) +def test_create_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["management_server"] = { + "name": "name_value", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": 1, + "management_uri": {"web_ui": "web_ui_value", "api": "api_value"}, + "workforce_identity_based_management_uri": { + "first_party_management_uri": "first_party_management_uri_value", + "third_party_management_uri": "third_party_management_uri_value", + }, + "state": 1, + "networks": [{"network": "network_value", "peering_mode": 1}], + "etag": "etag_value", + "oauth2_client_id": "oauth2_client_id_value", + "workforce_identity_based_oauth2_client_id": { + "first_party_oauth2_client_id": "first_party_oauth2_client_id_value", + "third_party_oauth2_client_id": "third_party_oauth2_client_id_value", + }, + "ba_proxy_uri": ["ba_proxy_uri_value1", "ba_proxy_uri_value2"], + "satisfies_pzs": {"value": True}, + "satisfies_pzi": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupdr.CreateManagementServerRequest.meta.fields["management_server"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["management_server"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["management_server"][field])): + del request_init["management_server"][field][i][subfield] + else: + del request_init["management_server"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_management_server(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.CreateManagementServerRequest.pb( + backupdr.CreateManagementServerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupdr.CreateManagementServerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_management_server_rest_bad_request( + request_type=backupdr.DeleteManagementServerRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.DeleteManagementServerRequest, + dict, + ], +) +def test_delete_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_management_server(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_delete_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.DeleteManagementServerRequest.pb( + backupdr.DeleteManagementServerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupdr.DeleteManagementServerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_backup_vault_rest_bad_request( + request_type=backupvault.CreateBackupVaultRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_backup_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.CreateBackupVaultRequest, + dict, + ], +) +def test_create_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup_vault"] = { + "name": "name_value", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_minimum_enforced_retention_duration": {"seconds": 751, "nanos": 543}, + "backup_retention_inheritance": 1, + "deletable": True, + "etag": "etag_value", + "state": 1, + "effective_time": {}, + "backup_count": 1278, + "service_account": "service_account_value", + "total_stored_bytes": 1946, + "uid": "uid_value", + "annotations": {}, + "access_restriction": 1, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupvault.CreateBackupVaultRequest.meta.fields["backup_vault"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["backup_vault"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["backup_vault"][field])): + del request_init["backup_vault"][field][i][subfield] + else: + del request_init["backup_vault"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_backup_vault(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.CreateBackupVaultRequest.pb( + backupvault.CreateBackupVaultRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupvault.CreateBackupVaultRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_backup_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_vaults_rest_bad_request( + request_type=backupvault.ListBackupVaultsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_backup_vaults(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupVaultsRequest, + dict, + ], +) +def test_list_backup_vaults_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_backup_vaults(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupVaultsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_backup_vaults_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_vaults" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_vaults_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backup_vaults" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.ListBackupVaultsRequest.pb( + backupvault.ListBackupVaultsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.ListBackupVaultsResponse.to_json( + backupvault.ListBackupVaultsResponse() + ) + req.return_value.content = return_value + + request = backupvault.ListBackupVaultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.ListBackupVaultsResponse() + post_with_metadata.return_value = ( + backupvault.ListBackupVaultsResponse(), + metadata, + ) + + client.list_backup_vaults( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_usable_backup_vaults_rest_bad_request( + request_type=backupvault.FetchUsableBackupVaultsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.fetch_usable_backup_vaults(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchUsableBackupVaultsRequest, + dict, + ], +) +def test_fetch_usable_backup_vaults_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchUsableBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.fetch_usable_backup_vaults(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchUsableBackupVaultsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_usable_backup_vaults_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_fetch_usable_backup_vaults" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_usable_backup_vaults_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_fetch_usable_backup_vaults" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.FetchUsableBackupVaultsRequest.pb( + backupvault.FetchUsableBackupVaultsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.FetchUsableBackupVaultsResponse.to_json( + backupvault.FetchUsableBackupVaultsResponse() + ) + req.return_value.content = return_value + + request = backupvault.FetchUsableBackupVaultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.FetchUsableBackupVaultsResponse() + post_with_metadata.return_value = ( + backupvault.FetchUsableBackupVaultsResponse(), + metadata, + ) + + client.fetch_usable_backup_vaults( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_vault_rest_bad_request( + request_type=backupvault.GetBackupVaultRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_backup_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupVaultRequest, + dict, + ], +) +def test_get_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_backup_vault(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.BackupVault) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.deletable is True + assert response.etag == "etag_value" + assert response.state == backupvault.BackupVault.State.CREATING + assert response.backup_count == 1278 + assert response.service_account == "service_account_value" + assert response.total_stored_bytes == 1946 + assert response.uid == "uid_value" + assert ( + response.access_restriction + == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.GetBackupVaultRequest.pb( + backupvault.GetBackupVaultRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.BackupVault.to_json(backupvault.BackupVault()) + req.return_value.content = return_value + + request = backupvault.GetBackupVaultRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.BackupVault() + post_with_metadata.return_value = backupvault.BackupVault(), metadata + + client.get_backup_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_backup_vault_rest_bad_request( + request_type=backupvault.UpdateBackupVaultRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup_vault": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_backup_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupVaultRequest, + dict, + ], +) +def test_update_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup_vault": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + } + request_init["backup_vault"] = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_minimum_enforced_retention_duration": {"seconds": 751, "nanos": 543}, + "backup_retention_inheritance": 1, + "deletable": True, + "etag": "etag_value", + "state": 1, + "effective_time": {}, + "backup_count": 1278, + "service_account": "service_account_value", + "total_stored_bytes": 1946, + "uid": "uid_value", + "annotations": {}, + "access_restriction": 1, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupvault.UpdateBackupVaultRequest.meta.fields["backup_vault"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["backup_vault"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["backup_vault"][field])): + del request_init["backup_vault"][field][i][subfield] + else: + del request_init["backup_vault"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_backup_vault(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_backup_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.UpdateBackupVaultRequest.pb( + backupvault.UpdateBackupVaultRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupvault.UpdateBackupVaultRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_backup_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_backup_vault_rest_bad_request( + request_type=backupvault.DeleteBackupVaultRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_backup_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupVaultRequest, + dict, + ], +) +def test_delete_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_backup_vault(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.DeleteBackupVaultRequest.pb( + backupvault.DeleteBackupVaultRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupvault.DeleteBackupVaultRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_backup_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_data_sources_rest_bad_request( + request_type=backupvault.ListDataSourcesRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupVaults/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_data_sources(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListDataSourcesRequest, + dict, + ], +) +def test_list_data_sources_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupVaults/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_data_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_sources_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_data_sources" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_data_sources_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_data_sources" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.ListDataSourcesRequest.pb( + backupvault.ListDataSourcesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.ListDataSourcesResponse.to_json( + backupvault.ListDataSourcesResponse() + ) + req.return_value.content = return_value + + request = backupvault.ListDataSourcesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.ListDataSourcesResponse() + post_with_metadata.return_value = ( + backupvault.ListDataSourcesResponse(), + metadata, + ) + + client.list_data_sources( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_data_source_rest_bad_request( + request_type=backupvault.GetDataSourceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_data_source(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetDataSourceRequest, + dict, + ], +) +def test_get_data_source_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_data_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.DataSource) + assert response.name == "name_value" + assert response.state == backupvault.DataSource.State.CREATING + assert response.backup_count == 1278 + assert response.etag == "etag_value" + assert response.total_stored_bytes == 1946 + assert response.config_state == backupvault.BackupConfigState.ACTIVE + assert response.backup_blocked_by_vault_access_restriction is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_source_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_data_source" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_data_source_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_data_source" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.GetDataSourceRequest.pb( + backupvault.GetDataSourceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.DataSource.to_json(backupvault.DataSource()) + req.return_value.content = return_value + + request = backupvault.GetDataSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.DataSource() + post_with_metadata.return_value = backupvault.DataSource(), metadata + + client.get_data_source( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_data_source_rest_bad_request( + request_type=backupvault.UpdateDataSourceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "data_source": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_data_source(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateDataSourceRequest, + dict, + ], +) +def test_update_data_source_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "data_source": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + } + request_init["data_source"] = { + "data_source_gcp_resource": { + "compute_instance_datasource_properties": { + "name": "name_value", + "description": "description_value", + "machine_type": "machine_type_value", + "total_disk_count": 1718, + "total_disk_size_gb": 1904, + }, + "cloud_sql_instance_datasource_properties": { + "name": "name_value", + "database_installed_version": "database_installed_version_value", + "instance_create_time": {"seconds": 751, "nanos": 543}, + "instance_tier": "instance_tier_value", + }, + "alloy_db_cluster_datasource_properties": { + "name": "name_value", + "pitr_windows": [ + {"start_time": {}, "end_time": {}, "log_retention_days": 1929} + ], + "cluster_uid": "cluster_uid_value", + }, + "disk_datasource_properties": { + "name": "name_value", + "description": "description_value", + "type_": "type__value", + "size_gb": 739, + }, + "gcp_resourcename": "gcp_resourcename_value", + "location": "location_value", + "type_": "type__value", + }, + "data_source_backup_appliance_application": { + "application_name": "application_name_value", + "backup_appliance": "backup_appliance_value", + "appliance_id": 1241, + "type_": "type__value", + "application_id": 1472, + "hostname": "hostname_value", + "host_id": 746, + }, + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4", + "state": 1, + "labels": {}, + "create_time": {}, + "update_time": {}, + "backup_count": 1278, + "etag": "etag_value", + "total_stored_bytes": 1946, + "config_state": 1, + "backup_config_info": { + "gcp_backup_config": { + "backup_plan": "backup_plan_value", + "backup_plan_description": "backup_plan_description_value", + "backup_plan_association": "backup_plan_association_value", + "backup_plan_rules": [ + "backup_plan_rules_value1", + "backup_plan_rules_value2", + ], + "backup_plan_revision_name": "backup_plan_revision_name_value", + "backup_plan_revision_id": "backup_plan_revision_id_value", + "auto_protection_policy_binding": "auto_protection_policy_binding_value", + }, + "backup_appliance_backup_config": { + "backup_appliance_name": "backup_appliance_name_value", + "backup_appliance_id": 1966, + "sla_id": 620, + "application_name": "application_name_value", + "host_name": "host_name_value", + "slt_name": "slt_name_value", + "slp_name": "slp_name_value", + }, + "last_backup_state": 1, + "last_successful_backup_consistency_time": {}, + "last_backup_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + }, + "backup_blocked_by_vault_access_restriction": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupvault.UpdateDataSourceRequest.meta.fields["data_source"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_source"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_source"][field])): + del request_init["data_source"][field][i][subfield] + else: + del request_init["data_source"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_data_source(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_source_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_data_source" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_data_source_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_data_source" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.UpdateDataSourceRequest.pb( + backupvault.UpdateDataSourceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupvault.UpdateDataSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_data_source( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backups_rest_bad_request(request_type=backupvault.ListBackupsRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_backups(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupsRequest, + dict, + ], +) +def test_list_backups_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_backups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_backups_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backups" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backups_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backups" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.ListBackupsRequest.pb(backupvault.ListBackupsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.ListBackupsResponse.to_json( + backupvault.ListBackupsResponse() + ) + req.return_value.content = return_value + + request = backupvault.ListBackupsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.ListBackupsResponse() + post_with_metadata.return_value = backupvault.ListBackupsResponse(), metadata + + client.list_backups( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_backups_for_resource_type_rest_bad_request( + request_type=backupvault.FetchBackupsForResourceTypeRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.fetch_backups_for_resource_type(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchBackupsForResourceTypeRequest, + dict, + ], +) +def test_fetch_backups_for_resource_type_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.fetch_backups_for_resource_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchBackupsForResourceTypePager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_backups_for_resource_type_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_fetch_backups_for_resource_type" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_backups_for_resource_type_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_fetch_backups_for_resource_type" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.FetchBackupsForResourceTypeRequest.pb( + backupvault.FetchBackupsForResourceTypeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.FetchBackupsForResourceTypeResponse.to_json( + backupvault.FetchBackupsForResourceTypeResponse() + ) + req.return_value.content = return_value + + request = backupvault.FetchBackupsForResourceTypeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.FetchBackupsForResourceTypeResponse() + post_with_metadata.return_value = ( + backupvault.FetchBackupsForResourceTypeResponse(), + metadata, + ) + + client.fetch_backups_for_resource_type( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_rest_bad_request(request_type=backupvault.GetBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupRequest, + dict, + ], +) +def test_get_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupvault.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_backup(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.Backup) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.etag == "etag_value" + assert response.state == backupvault.Backup.State.CREATING + assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED + assert response.resource_size_bytes == 2056 + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.kms_key_versions == ["kms_key_versions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.BackupDRRestInterceptor, "pre_get_backup") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.GetBackupRequest.pb(backupvault.GetBackupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupvault.Backup.to_json(backupvault.Backup()) + req.return_value.content = return_value + + request = backupvault.GetBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.Backup() + post_with_metadata.return_value = backupvault.Backup(), metadata + + client.get_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_backup_rest_bad_request(request_type=backupvault.UpdateBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupRequest, + dict, + ], +) +def test_update_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + } + request_init["backup"] = { + "compute_instance_backup_properties": { + "description": "description_value", + "tags": {"items": ["items_value1", "items_value2"]}, + "machine_type": "machine_type_value", + "can_ip_forward": True, + "network_interface": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "ip_address": "ip_address_value", + "ipv6_address": "ipv6_address_value", + "internal_ipv6_prefix_length": 2831, + "name": "name_value", + "access_configs": [ + { + "type_": 1, + "name": "name_value", + "external_ip": "external_ip_value", + "external_ipv6": "external_ipv6_value", + "external_ipv6_prefix_length": 2837, + "set_public_ptr": True, + "public_ptr_domain_name": "public_ptr_domain_name_value", + "network_tier": 1, + } + ], + "ipv6_access_configs": {}, + "alias_ip_ranges": [ + { + "ip_cidr_range": "ip_cidr_range_value", + "subnetwork_range_name": "subnetwork_range_name_value", + } + ], + "stack_type": 1, + "ipv6_access_type": 1, + "queue_count": 1197, + "nic_type": 1, + "network_attachment": "network_attachment_value", + } + ], + "disk": [ + { + "initialize_params": { + "disk_name": "disk_name_value", + "replica_zones": [ + "replica_zones_value1", + "replica_zones_value2", + ], + }, + "device_name": "device_name_value", + "kind": "kind_value", + "disk_type_deprecated": 1, + "mode": 1, + "source": "source_value", + "index": 536, + "boot": True, + "auto_delete": True, + "license_": ["license__value1", "license__value2"], + "disk_interface": 1, + "guest_os_feature": [{"type_": 1}], + "disk_encryption_key": { + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + }, + "disk_size_gb": 1261, + "saved_state": 1, + "disk_type": "disk_type_value", + "type_": 1, + } + ], + "metadata": {"items": [{"key": "key_value", "value": "value_value"}]}, + "service_account": [ + {"email": "email_value", "scopes": ["scopes_value1", "scopes_value2"]} + ], + "scheduling": { + "on_host_maintenance": 1, + "automatic_restart": True, + "preemptible": True, + "node_affinities": [ + { + "key": "key_value", + "operator": 1, + "values": ["values_value1", "values_value2"], + } + ], + "min_node_cpus": 1379, + "provisioning_model": 1, + "instance_termination_action": 1, + "local_ssd_recovery_timeout": {"seconds": 751, "nanos": 543}, + }, + "guest_accelerator": [ + { + "accelerator_type": "accelerator_type_value", + "accelerator_count": 1805, + } + ], + "min_cpu_platform": "min_cpu_platform_value", + "key_revocation_action_type": 1, + "source_instance": "source_instance_value", + "labels": {}, + "guest_flush": True, + }, + "cloud_sql_instance_backup_properties": { + "database_installed_version": "database_installed_version_value", + "final_backup": True, + "source_instance": "source_instance_value", + "instance_create_time": {"seconds": 751, "nanos": 543}, + "instance_tier": "instance_tier_value", + "instance_delete_time": {}, + }, + "backup_appliance_backup_properties": { + "generation_id": 1368, + "finalize_time": {}, + "recovery_range_start_time": {}, + "recovery_range_end_time": {}, + }, + "alloy_db_backup_properties": { + "description": "description_value", + "stored_bytes": 1303, + "chain_id": "chain_id_value", + "database_version": "database_version_value", + }, + "disk_backup_properties": { + "description": "description_value", + "licenses": ["licenses_value1", "licenses_value2"], + "guest_os_feature": {}, + "architecture": 1, + "type_": "type__value", + "size_gb": 739, + "region": "region_value", + "zone": "zone_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "source_disk": "source_disk_value", + "access_mode": "access_mode_value", + "provisioned_iops": 1740, + "provisioned_throughput": 2411, + "physical_block_size_bytes": 2663, + "enable_confidential_compute": True, + "storage_pool": "storage_pool_value", + "labels": {}, + "guest_flush": True, + }, + "gcp_backup_plan_info": { + "backup_plan": "backup_plan_value", + "backup_plan_rule_id": "backup_plan_rule_id_value", + "backup_plan_revision_name": "backup_plan_revision_name_value", + "backup_plan_revision_id": "backup_plan_revision_id_value", + }, + "gcp_resource": { + "gcp_resourcename": "gcp_resourcename_value", + "location": "location_value", + "type_": "type__value", + }, + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5", + "description": "description_value", + "create_time": {}, + "update_time": {}, + "labels": {}, + "enforced_retention_end_time": {}, + "backup_retention_inheritance": 1, + "expire_time": {}, + "consistency_time": {}, + "etag": "etag_value", + "state": 1, + "service_locks": [ + { + "backup_appliance_lock_info": { + "job_name": "job_name_value", + "backup_image": "backup_image_value", + "sla_id": 620, + "backup_appliance_id": 1966, + "backup_appliance_name": "backup_appliance_name_value", + "lock_reason": "lock_reason_value", + }, + "service_lock_info": {"operation": "operation_value"}, + "lock_until_time": {}, + } + ], + "backup_appliance_locks": {}, + "backup_type": 1, + "resource_size_bytes": 2056, + "satisfies_pzs": True, + "satisfies_pzi": True, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupvault.UpdateBackupRequest.meta.fields["backup"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["backup"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["backup"][field])): + del request_init["backup"][field][i][subfield] + else: + del request_init["backup"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_backup(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.UpdateBackupRequest.pb( + backupvault.UpdateBackupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupvault.UpdateBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_backup_rest_bad_request(request_type=backupvault.DeleteBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupRequest, + dict, + ], +) +def test_delete_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_backup(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.DeleteBackupRequest.pb( + backupvault.DeleteBackupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupvault.DeleteBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_restore_backup_rest_bad_request(request_type=backupvault.RestoreBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.restore_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.RestoreBackupRequest, + dict, + ], +) +def test_restore_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.restore_backup(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_restore_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_restore_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_restore_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.RestoreBackupRequest.pb( + backupvault.RestoreBackupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupvault.RestoreBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.restore_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_backup_plan_rest_bad_request( + request_type=backupplan.CreateBackupPlanRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_backup_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.CreateBackupPlanRequest, + dict, + ], +) +def test_create_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup_plan"] = { + "disk_backup_plan_properties": {"guest_flush": True}, + "compute_instance_backup_plan_properties": {"guest_flush": True}, + "name": "name_value", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_rules": [ + { + "standard_schedule": { + "recurrence_type": 1, + "hourly_frequency": 1748, + "days_of_week": [1], + "days_of_month": [1387, 1388], + "week_day_of_month": {"week_of_month": 1, "day_of_week": 1}, + "months": [1], + "backup_window": { + "start_hour_of_day": 1820, + "end_hour_of_day": 1573, + }, + "time_zone": "time_zone_value", + }, + "rule_id": "rule_id_value", + "backup_retention_days": 2237, + } + ], + "max_custom_on_demand_retention_days": 3723, + "state": 1, + "resource_type": "resource_type_value", + "etag": "etag_value", + "backup_vault": "backup_vault_value", + "backup_vault_service_account": "backup_vault_service_account_value", + "log_retention_days": 1929, + "supported_resource_types": [ + "supported_resource_types_value1", + "supported_resource_types_value2", + ], + "revision_id": "revision_id_value", + "revision_name": "revision_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupplan.CreateBackupPlanRequest.meta.fields["backup_plan"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["backup_plan"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["backup_plan"][field])): + del request_init["backup_plan"][field][i][subfield] + else: + del request_init["backup_plan"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_backup_plan(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.CreateBackupPlanRequest.pb( + backupplan.CreateBackupPlanRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupplan.CreateBackupPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_backup_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_backup_plan_rest_bad_request( + request_type=backupplan.UpdateBackupPlanRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup_plan": { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_backup_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.UpdateBackupPlanRequest, + dict, + ], +) +def test_update_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup_plan": { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + } + request_init["backup_plan"] = { + "disk_backup_plan_properties": {"guest_flush": True}, + "compute_instance_backup_plan_properties": {"guest_flush": True}, + "name": "projects/sample1/locations/sample2/backupPlans/sample3", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_rules": [ + { + "standard_schedule": { + "recurrence_type": 1, + "hourly_frequency": 1748, + "days_of_week": [1], + "days_of_month": [1387, 1388], + "week_day_of_month": {"week_of_month": 1, "day_of_week": 1}, + "months": [1], + "backup_window": { + "start_hour_of_day": 1820, + "end_hour_of_day": 1573, + }, + "time_zone": "time_zone_value", + }, + "rule_id": "rule_id_value", + "backup_retention_days": 2237, + } + ], + "max_custom_on_demand_retention_days": 3723, + "state": 1, + "resource_type": "resource_type_value", + "etag": "etag_value", + "backup_vault": "backup_vault_value", + "backup_vault_service_account": "backup_vault_service_account_value", + "log_retention_days": 1929, + "supported_resource_types": [ + "supported_resource_types_value1", + "supported_resource_types_value2", + ], + "revision_id": "revision_id_value", + "revision_name": "revision_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupplan.UpdateBackupPlanRequest.meta.fields["backup_plan"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["backup_plan"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["backup_plan"][field])): + del request_init["backup_plan"][field][i][subfield] + else: + del request_init["backup_plan"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_backup_plan(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_backup_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.UpdateBackupPlanRequest.pb( + backupplan.UpdateBackupPlanRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupplan.UpdateBackupPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_backup_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_plan_rest_bad_request(request_type=backupplan.GetBackupPlanRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_backup_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRequest, + dict, + ], +) +def test_get_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlan( + name="name_value", + description="description_value", + max_custom_on_demand_retention_days=3723, + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_backup_plan(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.max_custom_on_demand_retention_days == 3723 + assert response.state == backupplan.BackupPlan.State.CREATING + assert response.resource_type == "resource_type_value" + assert response.etag == "etag_value" + assert response.backup_vault == "backup_vault_value" + assert response.backup_vault_service_account == "backup_vault_service_account_value" + assert response.log_retention_days == 1929 + assert response.supported_resource_types == ["supported_resource_types_value"] + assert response.revision_id == "revision_id_value" + assert response.revision_name == "revision_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.GetBackupPlanRequest.pb( + backupplan.GetBackupPlanRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupplan.BackupPlan.to_json(backupplan.BackupPlan()) + req.return_value.content = return_value + + request = backupplan.GetBackupPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.BackupPlan() + post_with_metadata.return_value = backupplan.BackupPlan(), metadata + + client.get_backup_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_plans_rest_bad_request( + request_type=backupplan.ListBackupPlansRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_backup_plans(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlansRequest, + dict, + ], +) +def test_list_backup_plans_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_backup_plans(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlansPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_backup_plans_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_plans" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_plans_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backup_plans" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.ListBackupPlansRequest.pb( + backupplan.ListBackupPlansRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupplan.ListBackupPlansResponse.to_json( + backupplan.ListBackupPlansResponse() + ) + req.return_value.content = return_value + + request = backupplan.ListBackupPlansRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.ListBackupPlansResponse() + post_with_metadata.return_value = backupplan.ListBackupPlansResponse(), metadata + + client.list_backup_plans( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_backup_plan_rest_bad_request( + request_type=backupplan.DeleteBackupPlanRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_backup_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.DeleteBackupPlanRequest, + dict, + ], +) +def test_delete_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_backup_plan(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.DeleteBackupPlanRequest.pb( + backupplan.DeleteBackupPlanRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupplan.DeleteBackupPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_backup_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_plan_revision_rest_bad_request( + request_type=backupplan.GetBackupPlanRevisionRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_backup_plan_revision(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRevisionRequest, + dict, + ], +) +def test_get_backup_plan_revision_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_backup_plan_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlanRevision) + assert response.name == "name_value" + assert response.revision_id == "revision_id_value" + assert response.state == backupplan.BackupPlanRevision.State.CREATING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_plan_revision_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_plan_revision" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_backup_plan_revision_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_backup_plan_revision" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.GetBackupPlanRevisionRequest.pb( + backupplan.GetBackupPlanRevisionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupplan.BackupPlanRevision.to_json( + backupplan.BackupPlanRevision() + ) + req.return_value.content = return_value + + request = backupplan.GetBackupPlanRevisionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.BackupPlanRevision() + post_with_metadata.return_value = backupplan.BackupPlanRevision(), metadata + + client.get_backup_plan_revision( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_plan_revisions_rest_bad_request( + request_type=backupplan.ListBackupPlanRevisionsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupPlans/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_backup_plan_revisions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlanRevisionsRequest, + dict, + ], +) +def test_list_backup_plan_revisions_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupPlans/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_backup_plan_revisions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlanRevisionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_backup_plan_revisions_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_plan_revisions" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_backup_plan_revisions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backup_plan_revisions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.ListBackupPlanRevisionsRequest.pb( + backupplan.ListBackupPlanRevisionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupplan.ListBackupPlanRevisionsResponse.to_json( + backupplan.ListBackupPlanRevisionsResponse() + ) + req.return_value.content = return_value + + request = backupplan.ListBackupPlanRevisionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.ListBackupPlanRevisionsResponse() + post_with_metadata.return_value = ( + backupplan.ListBackupPlanRevisionsResponse(), + metadata, + ) + + client.list_backup_plan_revisions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_backup_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.CreateBackupPlanAssociationRequest, + dict, + ], +) +def test_create_backup_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup_plan_association"] = { + "cloud_sql_instance_backup_plan_association_properties": { + "instance_create_time": {"seconds": 751, "nanos": 543} + }, + "alloydb_cluster_backup_plan_association_properties": { + "cluster_uid": "cluster_uid_value" + }, + "name": "name_value", + "resource_type": "resource_type_value", + "resource": "resource_value", + "backup_plan": "backup_plan_value", + "create_time": {}, + "update_time": {}, + "state": 1, + "rules_config_info": [ + { + "rule_id": "rule_id_value", + "last_backup_state": 1, + "last_backup_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "last_successful_backup_consistency_time": {}, + } + ], + "data_source": "data_source_value", + "backup_plan_revision_id": "backup_plan_revision_id_value", + "backup_plan_revision_name": "backup_plan_revision_name_value", + "auto_protection_policy_binding": "auto_protection_policy_binding_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupplanassociation.CreateBackupPlanAssociationRequest.meta.fields[ + "backup_plan_association" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "backup_plan_association" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["backup_plan_association"][field])): + del request_init["backup_plan_association"][field][i][subfield] + else: + del request_init["backup_plan_association"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_backup_plan_association(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_backup_plan_association_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_backup_plan_association" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_backup_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_backup_plan_association" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.CreateBackupPlanAssociationRequest.pb( + backupplanassociation.CreateBackupPlanAssociationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupplanassociation.CreateBackupPlanAssociationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_backup_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup_plan_association": { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_backup_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.UpdateBackupPlanAssociationRequest, + dict, + ], +) +def test_update_backup_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup_plan_association": { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + } + request_init["backup_plan_association"] = { + "cloud_sql_instance_backup_plan_association_properties": { + "instance_create_time": {"seconds": 751, "nanos": 543} + }, + "alloydb_cluster_backup_plan_association_properties": { + "cluster_uid": "cluster_uid_value" + }, + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3", + "resource_type": "resource_type_value", + "resource": "resource_value", + "backup_plan": "backup_plan_value", + "create_time": {}, + "update_time": {}, + "state": 1, + "rules_config_info": [ + { + "rule_id": "rule_id_value", + "last_backup_state": 1, + "last_backup_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "last_successful_backup_consistency_time": {}, + } + ], + "data_source": "data_source_value", + "backup_plan_revision_id": "backup_plan_revision_id_value", + "backup_plan_revision_name": "backup_plan_revision_name_value", + "auto_protection_policy_binding": "auto_protection_policy_binding_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = backupplanassociation.UpdateBackupPlanAssociationRequest.meta.fields[ + "backup_plan_association" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "backup_plan_association" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["backup_plan_association"][field])): + del request_init["backup_plan_association"][field][i][subfield] + else: + del request_init["backup_plan_association"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_backup_plan_association(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_backup_plan_association_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_plan_association" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_update_backup_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup_plan_association" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.UpdateBackupPlanAssociationRequest.pb( + backupplanassociation.UpdateBackupPlanAssociationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupplanassociation.UpdateBackupPlanAssociationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_backup_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.GetBackupPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_backup_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.GetBackupPlanAssociationRequest, + dict, + ], +) +def test_get_backup_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplanassociation.BackupPlanAssociation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_backup_plan_association(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplanassociation.BackupPlanAssociation) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert response.resource == "resource_value" + assert response.backup_plan == "backup_plan_value" + assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING + assert response.data_source == "data_source_value" + assert response.backup_plan_revision_id == "backup_plan_revision_id_value" + assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_plan_association_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_plan_association" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_backup_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_backup_plan_association" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.GetBackupPlanAssociationRequest.pb( + backupplanassociation.GetBackupPlanAssociationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupplanassociation.BackupPlanAssociation.to_json( + backupplanassociation.BackupPlanAssociation() + ) + req.return_value.content = return_value + + request = backupplanassociation.GetBackupPlanAssociationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplanassociation.BackupPlanAssociation() + post_with_metadata.return_value = ( + backupplanassociation.BackupPlanAssociation(), + metadata, + ) + + client.get_backup_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_plan_associations_rest_bad_request( + request_type=backupplanassociation.ListBackupPlanAssociationsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_backup_plan_associations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.ListBackupPlanAssociationsRequest, + dict, + ], +) +def test_list_backup_plan_associations_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_backup_plan_associations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlanAssociationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_backup_plan_associations_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_plan_associations" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_backup_plan_associations_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backup_plan_associations" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.ListBackupPlanAssociationsRequest.pb( + backupplanassociation.ListBackupPlanAssociationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupplanassociation.ListBackupPlanAssociationsResponse.to_json( + backupplanassociation.ListBackupPlanAssociationsResponse() + ) + req.return_value.content = return_value + + request = backupplanassociation.ListBackupPlanAssociationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + post_with_metadata.return_value = ( + backupplanassociation.ListBackupPlanAssociationsResponse(), + metadata, + ) + + client.list_backup_plan_associations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_backup_plan_associations_for_resource_type_rest_bad_request( + request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.fetch_backup_plan_associations_for_resource_type(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + dict, + ], +) +def test_fetch_backup_plan_associations_for_resource_type_rest_call_success( + request_type, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchBackupPlanAssociationsForResourceTypePager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_backup_plan_associations_for_resource_type_rest_interceptors( + null_interceptor, +): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_backup_plan_associations_for_resource_type", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_backup_plan_associations_for_resource_type_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_fetch_backup_plan_associations_for_resource_type", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest.pb( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + req.return_value.content = return_value + + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + post_with_metadata.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse(), + metadata, + ) + + client.fetch_backup_plan_associations_for_resource_type( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_backup_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.DeleteBackupPlanAssociationRequest, + dict, + ], +) +def test_delete_backup_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_backup_plan_association(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_plan_association_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_plan_association" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_delete_backup_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_backup_plan_association" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.DeleteBackupPlanAssociationRequest.pb( + backupplanassociation.DeleteBackupPlanAssociationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupplanassociation.DeleteBackupPlanAssociationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_backup_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_trigger_backup_rest_bad_request( + request_type=backupplanassociation.TriggerBackupRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.trigger_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.TriggerBackupRequest, + dict, + ], +) +def test_trigger_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.trigger_backup(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_trigger_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_trigger_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_trigger_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_trigger_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.TriggerBackupRequest.pb( + backupplanassociation.TriggerBackupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupplanassociation.TriggerBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.trigger_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_data_source_reference_rest_bad_request( + request_type=datasourcereference.GetDataSourceReferenceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataSourceReferences/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_data_source_reference(request) + + +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.GetDataSourceReferenceRequest, + dict, + ], +) +def test_get_data_source_reference_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataSourceReferences/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = datasourcereference.DataSourceReference.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_data_source_reference(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, datasourcereference.DataSourceReference) + assert response.name == "name_value" + assert response.data_source == "data_source_value" + assert ( + response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE + ) + assert response.data_source_backup_count == 2535 + assert response.total_stored_bytes == 1946 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_source_reference_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_data_source_reference" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_data_source_reference_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_data_source_reference" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = datasourcereference.GetDataSourceReferenceRequest.pb( + datasourcereference.GetDataSourceReferenceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = datasourcereference.DataSourceReference.to_json( + datasourcereference.DataSourceReference() + ) + req.return_value.content = return_value + + request = datasourcereference.GetDataSourceReferenceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = datasourcereference.DataSourceReference() + post_with_metadata.return_value = ( + datasourcereference.DataSourceReference(), + metadata, + ) + + client.get_data_source_reference( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_data_source_references_rest_bad_request( + request_type=datasourcereference.ListDataSourceReferencesRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_data_source_references(request) + + +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.ListDataSourceReferencesRequest, + dict, + ], +) +def test_list_data_source_references_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_data_source_references(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourceReferencesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_source_references_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_data_source_references" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_data_source_references_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_data_source_references" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = datasourcereference.ListDataSourceReferencesRequest.pb( + datasourcereference.ListDataSourceReferencesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = datasourcereference.ListDataSourceReferencesResponse.to_json( + datasourcereference.ListDataSourceReferencesResponse() + ) + req.return_value.content = return_value + + request = datasourcereference.ListDataSourceReferencesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = datasourcereference.ListDataSourceReferencesResponse() + post_with_metadata.return_value = ( + datasourcereference.ListDataSourceReferencesResponse(), + metadata, + ) + + client.list_data_source_references( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_data_source_references_for_resource_type_rest_bad_request( + request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.fetch_data_source_references_for_resource_type(request) + + +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + dict, + ], +) +def test_fetch_data_source_references_for_resource_type_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.fetch_data_source_references_for_resource_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDataSourceReferencesForResourceTypePager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_data_source_references_for_resource_type_rest_interceptors( + null_interceptor, +): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_data_source_references_for_resource_type", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_data_source_references_for_resource_type_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_fetch_data_source_references_for_resource_type", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest.pb( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + req.return_value.content = return_value + + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + post_with_metadata.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse(), + metadata, + ) + + client.fetch_data_source_references_for_resource_type( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_service_rest_bad_request( + request_type=backupdr.InitializeServiceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.initialize_service(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.InitializeServiceRequest, + dict, + ], +) +def test_initialize_service_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.initialize_service(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_initialize_service_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_initialize_service" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_initialize_service_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_initialize_service" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.InitializeServiceRequest.pb( + backupdr.InitializeServiceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupdr.InitializeServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.initialize_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.CreateAutoProtectionPolicyRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_auto_protection_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest, + dict, + ], +) +def test_create_auto_protection_policy_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["auto_protection_policy"] = { + "name": "name_value", + "description": "description_value", + "backup_plan_details": [ + {"resource_type": "resource_type_value", "backup_plan": "backup_plan_value"} + ], + "criteria": { + "matching_conditions": [ + { + "label_condition": { + "key": "key_value", + "values": ["values_value1", "values_value2"], + } + } + ] + }, + "state": 1, + "etag": "etag_value", + "binding_summary": {"project_count": 1407}, + "policy_evaluation_summary": { + "matching_resource_count": 2458, + "protected_resource_count": 2585, + "failed_resource_count": 2228, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = autoprotectionpolicy.CreateAutoProtectionPolicyRequest.meta.fields[ + "auto_protection_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "auto_protection_policy" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["auto_protection_policy"][field])): + del request_init["auto_protection_policy"][field][i][subfield] + else: + del request_init["auto_protection_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_auto_protection_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_auto_protection_policy_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_auto_protection_policy" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_auto_protection_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_auto_protection_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autoprotectionpolicy.CreateAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_auto_protection_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_auto_protection_policies_rest_bad_request( + request_type=autoprotectionpolicy.ListAutoProtectionPoliciesRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_auto_protection_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + dict, + ], +) +def test_list_auto_protection_policies_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_auto_protection_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_auto_protection_policies_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_auto_protection_policies" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_auto_protection_policies_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_auto_protection_policies" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autoprotectionpolicy.ListAutoProtectionPoliciesRequest.pb( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.to_json( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + ) + req.return_value.content = return_value + + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + post_with_metadata.return_value = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse(), + metadata, + ) + + client.list_auto_protection_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.GetAutoProtectionPolicyRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_auto_protection_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.GetAutoProtectionPolicyRequest, + dict, + ], +) +def test_get_auto_protection_policy_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_auto_protection_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_auto_protection_policy_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_auto_protection_policy" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_auto_protection_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_auto_protection_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autoprotectionpolicy.GetAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.GetAutoProtectionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = autoprotectionpolicy.AutoProtectionPolicy.to_json( + autoprotectionpolicy.AutoProtectionPolicy() + ) + req.return_value.content = return_value + + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autoprotectionpolicy.AutoProtectionPolicy() + post_with_metadata.return_value = ( + autoprotectionpolicy.AutoProtectionPolicy(), + metadata, + ) + + client.get_auto_protection_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "auto_protection_policy": { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_auto_protection_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, + dict, + ], +) +def test_update_auto_protection_policy_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "auto_protection_policy": { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + } + request_init["auto_protection_policy"] = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3", + "description": "description_value", + "backup_plan_details": [ + {"resource_type": "resource_type_value", "backup_plan": "backup_plan_value"} + ], + "criteria": { + "matching_conditions": [ + { + "label_condition": { + "key": "key_value", + "values": ["values_value1", "values_value2"], + } + } + ] + }, + "state": 1, + "etag": "etag_value", + "binding_summary": {"project_count": 1407}, + "policy_evaluation_summary": { + "matching_resource_count": 2458, + "protected_resource_count": 2585, + "failed_resource_count": 2228, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.meta.fields[ + "auto_protection_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "auto_protection_policy" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["auto_protection_policy"][field])): + del request_init["auto_protection_policy"][field][i][subfield] + else: + del request_init["auto_protection_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_auto_protection_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_auto_protection_policy_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_auto_protection_policy" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_update_auto_protection_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_auto_protection_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_auto_protection_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_auto_protection_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + dict, + ], +) +def test_delete_auto_protection_policy_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_auto_protection_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_auto_protection_policy_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_auto_protection_policy" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_delete_auto_protection_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_auto_protection_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_auto_protection_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_auto_protection_policy_binding_rest_bad_request( + request_type=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_auto_protection_policy_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + dict, + ], +) +def test_create_auto_protection_policy_binding_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request_init["auto_protection_policy_binding"] = { + "name": "name_value", + "description": "description_value", + "state": 1, + "scope": "scope_value", + "binding_evaluation_summary": { + "matching_resource_count": 2458, + "protected_resource_count": 2585, + "failed_resource_count": 2228, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.meta.fields[ + "auto_protection_policy_binding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "auto_protection_policy_binding" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["auto_protection_policy_binding"][field]) + ): + del request_init["auto_protection_policy_binding"][field][i][ + subfield + ] + else: + del request_init["auto_protection_policy_binding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_auto_protection_policy_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_auto_protection_policy_binding_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_auto_protection_policy_binding", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_auto_protection_policy_binding_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_create_auto_protection_policy_binding", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.pb( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_auto_protection_policy_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_auto_protection_policy_binding_rest_bad_request( + request_type=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_auto_protection_policy_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + dict, + ], +) +def test_get_auto_protection_policy_binding_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_auto_protection_policy_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING + ) + assert response.scope == "scope_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_auto_protection_policy_binding_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_auto_protection_policy_binding", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_auto_protection_policy_binding_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_auto_protection_policy_binding" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest.pb( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.to_json( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) + req.return_value.content = return_value + + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + post_with_metadata.return_value = ( + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + metadata, + ) + + client.get_auto_protection_policy_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_auto_protection_policy_bindings_rest_bad_request( + request_type=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_auto_protection_policy_bindings(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + dict, + ], +) +def test_list_auto_protection_policy_bindings_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_auto_protection_policy_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_auto_protection_policy_bindings_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_auto_protection_policy_bindings", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_auto_protection_policy_bindings_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_list_auto_protection_policy_bindings", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest.pb( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.to_json( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + req.return_value.content = return_value + + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + post_with_metadata.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse(), + metadata, + ) + + client.list_auto_protection_policy_bindings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_applied_auto_protection_policies_rest_bad_request( + request_type=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_applied_auto_protection_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + dict, + ], +) +def test_list_applied_auto_protection_policies_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_applied_auto_protection_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_applied_auto_protection_policies_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_applied_auto_protection_policies", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_applied_auto_protection_policies_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_list_applied_auto_protection_policies", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest.pb( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.to_json( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + req.return_value.content = return_value + + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + post_with_metadata.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse(), + metadata, + ) + + client.list_applied_auto_protection_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initiate_delete_auto_protection_policy_binding_rest_bad_request( + request_type=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.initiate_delete_auto_protection_policy_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + dict, + ], +) +def test_initiate_delete_auto_protection_policy_binding_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_initiate_delete_auto_protection_policy_binding_rest_interceptors( + null_interceptor, +): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_initiate_delete_auto_protection_policy_binding", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_initiate_delete_auto_protection_policy_binding_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_initiate_delete_auto_protection_policy_binding", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest.pb( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.initiate_delete_auto_protection_policy_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_binding_matching_resource_rest_bad_request( + request_type=bindingmatchingresource.GetBindingMatchingResourceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4/matchingResources/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_binding_matching_resource(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.GetBindingMatchingResourceRequest, + dict, + ], +) +def test_get_binding_matching_resource_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4/matchingResources/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.BindingMatchingResource( + name="name_value", + resource="resource_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bindingmatchingresource.BindingMatchingResource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_binding_matching_resource(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bindingmatchingresource.BindingMatchingResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_binding_matching_resource_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_binding_matching_resource" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_binding_matching_resource_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_binding_matching_resource" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bindingmatchingresource.GetBindingMatchingResourceRequest.pb( + bindingmatchingresource.GetBindingMatchingResourceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bindingmatchingresource.BindingMatchingResource.to_json( + bindingmatchingresource.BindingMatchingResource() + ) + req.return_value.content = return_value + + request = bindingmatchingresource.GetBindingMatchingResourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bindingmatchingresource.BindingMatchingResource() + post_with_metadata.return_value = ( + bindingmatchingresource.BindingMatchingResource(), + metadata, + ) + + client.get_binding_matching_resource( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_binding_matching_resources_rest_bad_request( + request_type=bindingmatchingresource.ListBindingMatchingResourcesRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_binding_matching_resources(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.ListBindingMatchingResourcesRequest, + dict, + ], +) +def test_list_binding_matching_resources_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_binding_matching_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBindingMatchingResourcesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_binding_matching_resources_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_binding_matching_resources" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_binding_matching_resources_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_binding_matching_resources" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bindingmatchingresource.ListBindingMatchingResourcesRequest.pb( + bindingmatchingresource.ListBindingMatchingResourcesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse.to_json( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + ) + req.return_value.content = return_value + + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + post_with_metadata.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse(), + metadata, + ) + + client.list_binding_matching_resources( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/managementServers/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/managementServers/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/managementServers/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_management_servers_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + client.list_management_servers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_management_server_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + client.get_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_management_server_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + client.create_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_management_server_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + client.delete_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_backup_vault_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + client.create_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_vaults_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + client.list_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_usable_backup_vaults_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + client.fetch_usable_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_vault_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + client.get_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_vault_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + client.update_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_vault_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + client.delete_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_data_sources_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_data_source_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_data_source_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backups_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + client.list_backups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_backups_for_resource_type_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + client.fetch_backups_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + client.get_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + client.update_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + client.delete_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_backup_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + client.restore_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_backup_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + client.create_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + client.update_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + client.get_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_plans_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + client.list_backup_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + client.delete_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_plan_revision_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + client.get_backup_plan_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_plan_revisions_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + client.list_backup_plan_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_backup_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + client.create_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_backup_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + client.update_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_backup_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + client.get_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_backup_plan_associations_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + client.list_backup_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_backup_plan_associations_for_resource_type_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + client.fetch_backup_plan_associations_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_backup_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + client.delete_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_trigger_backup_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + client.trigger_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_data_source_reference_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + client.get_data_source_reference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_data_source_references_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + client.list_data_source_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_data_source_references_for_resource_type_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + client.fetch_data_source_references_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_initialize_service_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + client.create_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_auto_protection_policies_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + client.update_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + client.delete_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_auto_protection_policy_binding_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + client.create_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_auto_protection_policy_binding_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_auto_protection_policy_bindings_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_applied_auto_protection_policies_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_initiate_delete_auto_protection_policy_binding_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + client.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_binding_matching_resource_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + client.get_binding_matching_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_binding_matching_resources_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request_msg + + +def test_backup_dr_rest_lro_client(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BackupDRGrpcTransport, + ) + + +def test_backup_dr_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BackupDRTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_backup_dr_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr.transports.BackupDRTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.BackupDRTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_management_servers", + "get_management_server", + "create_management_server", + "delete_management_server", + "create_backup_vault", + "list_backup_vaults", + "fetch_usable_backup_vaults", + "get_backup_vault", + "update_backup_vault", + "delete_backup_vault", + "list_data_sources", + "get_data_source", + "update_data_source", + "list_backups", + "fetch_backups_for_resource_type", + "get_backup", + "update_backup", + "delete_backup", + "restore_backup", + "create_backup_plan", + "update_backup_plan", + "get_backup_plan", + "list_backup_plans", + "delete_backup_plan", + "get_backup_plan_revision", + "list_backup_plan_revisions", + "create_backup_plan_association", + "update_backup_plan_association", + "get_backup_plan_association", + "list_backup_plan_associations", + "fetch_backup_plan_associations_for_resource_type", + "delete_backup_plan_association", + "trigger_backup", + "get_data_source_reference", + "list_data_source_references", + "fetch_data_source_references_for_resource_type", + "initialize_service", + "create_auto_protection_policy", + "list_auto_protection_policies", + "get_auto_protection_policy", + "update_auto_protection_policy", + "delete_auto_protection_policy", + "create_auto_protection_policy_binding", + "get_auto_protection_policy_binding", + "list_auto_protection_policy_bindings", + "list_applied_auto_protection_policies", + "initiate_delete_auto_protection_policy_binding", + "get_binding_matching_resource", + "list_binding_matching_resources", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_backup_dr_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr.transports.BackupDRTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BackupDRTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_backup_dr_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr.transports.BackupDRTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BackupDRTransport() + adc.assert_called_once() + + +def test_backup_dr_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + BackupDRClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDRGrpcTransport, + transports.BackupDRGrpcAsyncIOTransport, + ], +) +def test_backup_dr_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDRGrpcTransport, + transports.BackupDRGrpcAsyncIOTransport, + transports.BackupDRRestTransport, + ], +) +def test_backup_dr_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.BackupDRGrpcTransport, grpc_helpers), + (transports.BackupDRGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_backup_dr_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "backupdr.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="backupdr.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.BackupDRGrpcTransport, transports.BackupDRGrpcAsyncIOTransport], +) +def test_backup_dr_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_backup_dr_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.BackupDRRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_backup_dr_host_no_port(transport_name): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="backupdr.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "backupdr.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_backup_dr_host_with_port(transport_name): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="backupdr.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "backupdr.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_backup_dr_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BackupDRClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BackupDRClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_management_servers._session + session2 = client2.transport.list_management_servers._session + assert session1 != session2 + session1 = client1.transport.get_management_server._session + session2 = client2.transport.get_management_server._session + assert session1 != session2 + session1 = client1.transport.create_management_server._session + session2 = client2.transport.create_management_server._session + assert session1 != session2 + session1 = client1.transport.delete_management_server._session + session2 = client2.transport.delete_management_server._session + assert session1 != session2 + session1 = client1.transport.create_backup_vault._session + session2 = client2.transport.create_backup_vault._session + assert session1 != session2 + session1 = client1.transport.list_backup_vaults._session + session2 = client2.transport.list_backup_vaults._session + assert session1 != session2 + session1 = client1.transport.fetch_usable_backup_vaults._session + session2 = client2.transport.fetch_usable_backup_vaults._session + assert session1 != session2 + session1 = client1.transport.get_backup_vault._session + session2 = client2.transport.get_backup_vault._session + assert session1 != session2 + session1 = client1.transport.update_backup_vault._session + session2 = client2.transport.update_backup_vault._session + assert session1 != session2 + session1 = client1.transport.delete_backup_vault._session + session2 = client2.transport.delete_backup_vault._session + assert session1 != session2 + session1 = client1.transport.list_data_sources._session + session2 = client2.transport.list_data_sources._session + assert session1 != session2 + session1 = client1.transport.get_data_source._session + session2 = client2.transport.get_data_source._session + assert session1 != session2 + session1 = client1.transport.update_data_source._session + session2 = client2.transport.update_data_source._session + assert session1 != session2 + session1 = client1.transport.list_backups._session + session2 = client2.transport.list_backups._session + assert session1 != session2 + session1 = client1.transport.fetch_backups_for_resource_type._session + session2 = client2.transport.fetch_backups_for_resource_type._session + assert session1 != session2 + session1 = client1.transport.get_backup._session + session2 = client2.transport.get_backup._session + assert session1 != session2 + session1 = client1.transport.update_backup._session + session2 = client2.transport.update_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 + session1 = client1.transport.restore_backup._session + session2 = client2.transport.restore_backup._session + assert session1 != session2 + session1 = client1.transport.create_backup_plan._session + session2 = client2.transport.create_backup_plan._session + assert session1 != session2 + session1 = client1.transport.update_backup_plan._session + session2 = client2.transport.update_backup_plan._session + assert session1 != session2 + session1 = client1.transport.get_backup_plan._session + session2 = client2.transport.get_backup_plan._session + assert session1 != session2 + session1 = client1.transport.list_backup_plans._session + session2 = client2.transport.list_backup_plans._session + assert session1 != session2 + session1 = client1.transport.delete_backup_plan._session + session2 = client2.transport.delete_backup_plan._session + assert session1 != session2 + session1 = client1.transport.get_backup_plan_revision._session + session2 = client2.transport.get_backup_plan_revision._session + assert session1 != session2 + session1 = client1.transport.list_backup_plan_revisions._session + session2 = client2.transport.list_backup_plan_revisions._session + assert session1 != session2 + session1 = client1.transport.create_backup_plan_association._session + session2 = client2.transport.create_backup_plan_association._session + assert session1 != session2 + session1 = client1.transport.update_backup_plan_association._session + session2 = client2.transport.update_backup_plan_association._session + assert session1 != session2 + session1 = client1.transport.get_backup_plan_association._session + session2 = client2.transport.get_backup_plan_association._session + assert session1 != session2 + session1 = client1.transport.list_backup_plan_associations._session + session2 = client2.transport.list_backup_plan_associations._session + assert session1 != session2 + session1 = ( + client1.transport.fetch_backup_plan_associations_for_resource_type._session + ) + session2 = ( + client2.transport.fetch_backup_plan_associations_for_resource_type._session + ) + assert session1 != session2 + session1 = client1.transport.delete_backup_plan_association._session + session2 = client2.transport.delete_backup_plan_association._session + assert session1 != session2 + session1 = client1.transport.trigger_backup._session + session2 = client2.transport.trigger_backup._session + assert session1 != session2 + session1 = client1.transport.get_data_source_reference._session + session2 = client2.transport.get_data_source_reference._session + assert session1 != session2 + session1 = client1.transport.list_data_source_references._session + session2 = client2.transport.list_data_source_references._session + assert session1 != session2 + session1 = client1.transport.fetch_data_source_references_for_resource_type._session + session2 = client2.transport.fetch_data_source_references_for_resource_type._session + assert session1 != session2 + session1 = client1.transport.initialize_service._session + session2 = client2.transport.initialize_service._session + assert session1 != session2 + session1 = client1.transport.create_auto_protection_policy._session + session2 = client2.transport.create_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.list_auto_protection_policies._session + session2 = client2.transport.list_auto_protection_policies._session + assert session1 != session2 + session1 = client1.transport.get_auto_protection_policy._session + session2 = client2.transport.get_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.update_auto_protection_policy._session + session2 = client2.transport.update_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.delete_auto_protection_policy._session + session2 = client2.transport.delete_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.create_auto_protection_policy_binding._session + session2 = client2.transport.create_auto_protection_policy_binding._session + assert session1 != session2 + session1 = client1.transport.get_auto_protection_policy_binding._session + session2 = client2.transport.get_auto_protection_policy_binding._session + assert session1 != session2 + session1 = client1.transport.list_auto_protection_policy_bindings._session + session2 = client2.transport.list_auto_protection_policy_bindings._session + assert session1 != session2 + session1 = client1.transport.list_applied_auto_protection_policies._session + session2 = client2.transport.list_applied_auto_protection_policies._session + assert session1 != session2 + session1 = client1.transport.initiate_delete_auto_protection_policy_binding._session + session2 = client2.transport.initiate_delete_auto_protection_policy_binding._session + assert session1 != session2 + session1 = client1.transport.get_binding_matching_resource._session + session2 = client2.transport.get_binding_matching_resource._session + assert session1 != session2 + session1 = client1.transport.list_binding_matching_resources._session + session2 = client2.transport.list_binding_matching_resources._session + assert session1 != session2 + + +def test_backup_dr_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BackupDRGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_backup_dr_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BackupDRGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.BackupDRGrpcTransport, transports.BackupDRGrpcAsyncIOTransport], +) +def test_backup_dr_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.BackupDRGrpcTransport, transports.BackupDRGrpcAsyncIOTransport], +) +def test_backup_dr_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_backup_dr_grpc_lro_client(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_backup_dr_grpc_lro_async_client(): + client = BackupDRAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_applied_auto_protection_policy_path(): + project = "squid" + location = "clam" + applied_auto_protection_policy = "whelk" + expected = "projects/{project}/locations/{location}/appliedAutoProtectionPolicies/{applied_auto_protection_policy}".format( + project=project, + location=location, + applied_auto_protection_policy=applied_auto_protection_policy, + ) + actual = BackupDRClient.applied_auto_protection_policy_path( + project, location, applied_auto_protection_policy + ) + assert expected == actual + + +def test_parse_applied_auto_protection_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "applied_auto_protection_policy": "nudibranch", + } + path = BackupDRClient.applied_auto_protection_policy_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_applied_auto_protection_policy_path(path) + assert expected == actual + + +def test_auto_protection_policy_path(): + project = "cuttlefish" + location = "mussel" + auto_protection_policy = "winkle" + expected = "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + ) + actual = BackupDRClient.auto_protection_policy_path( + project, location, auto_protection_policy + ) + assert expected == actual + + +def test_parse_auto_protection_policy_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "auto_protection_policy": "abalone", + } + path = BackupDRClient.auto_protection_policy_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_auto_protection_policy_path(path) + assert expected == actual + + +def test_auto_protection_policy_binding_path(): + project = "squid" + location = "clam" + auto_protection_policy = "whelk" + binding = "octopus" + expected = "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + ) + actual = BackupDRClient.auto_protection_policy_binding_path( + project, location, auto_protection_policy, binding + ) + assert expected == actual + + +def test_parse_auto_protection_policy_binding_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "auto_protection_policy": "cuttlefish", + "binding": "mussel", + } + path = BackupDRClient.auto_protection_policy_binding_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_auto_protection_policy_binding_path(path) + assert expected == actual + + +def test_backup_path(): + project = "winkle" + location = "nautilus" + backupvault = "scallop" + datasource = "abalone" + backup = "squid" + expected = "projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource}/backups/{backup}".format( + project=project, + location=location, + backupvault=backupvault, + datasource=datasource, + backup=backup, + ) + actual = BackupDRClient.backup_path( + project, location, backupvault, datasource, backup + ) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "clam", + "location": "whelk", + "backupvault": "octopus", + "datasource": "oyster", + "backup": "nudibranch", + } + path = BackupDRClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_backup_path(path) + assert expected == actual + + +def test_backup_plan_path(): + project = "cuttlefish" + location = "mussel" + backup_plan = "winkle" + expected = ( + "projects/{project}/locations/{location}/backupPlans/{backup_plan}".format( + project=project, + location=location, + backup_plan=backup_plan, + ) + ) + actual = BackupDRClient.backup_plan_path(project, location, backup_plan) + assert expected == actual + + +def test_parse_backup_plan_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "backup_plan": "abalone", + } + path = BackupDRClient.backup_plan_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_backup_plan_path(path) + assert expected == actual + + +def test_backup_plan_association_path(): + project = "squid" + location = "clam" + backup_plan_association = "whelk" + expected = "projects/{project}/locations/{location}/backupPlanAssociations/{backup_plan_association}".format( + project=project, + location=location, + backup_plan_association=backup_plan_association, + ) + actual = BackupDRClient.backup_plan_association_path( + project, location, backup_plan_association + ) + assert expected == actual + + +def test_parse_backup_plan_association_path(): + expected = { + "project": "octopus", + "location": "oyster", + "backup_plan_association": "nudibranch", + } + path = BackupDRClient.backup_plan_association_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_backup_plan_association_path(path) + assert expected == actual + + +def test_backup_plan_revision_path(): + project = "cuttlefish" + location = "mussel" + backup_plan = "winkle" + revision = "nautilus" + expected = "projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision}".format( + project=project, + location=location, + backup_plan=backup_plan, + revision=revision, + ) + actual = BackupDRClient.backup_plan_revision_path( + project, location, backup_plan, revision + ) + assert expected == actual + + +def test_parse_backup_plan_revision_path(): + expected = { + "project": "scallop", + "location": "abalone", + "backup_plan": "squid", + "revision": "clam", + } + path = BackupDRClient.backup_plan_revision_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_backup_plan_revision_path(path) + assert expected == actual + + +def test_backup_vault_path(): + project = "whelk" + location = "octopus" + backupvault = "oyster" + expected = ( + "projects/{project}/locations/{location}/backupVaults/{backupvault}".format( + project=project, + location=location, + backupvault=backupvault, + ) + ) + actual = BackupDRClient.backup_vault_path(project, location, backupvault) + assert expected == actual + + +def test_parse_backup_vault_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "backupvault": "mussel", + } + path = BackupDRClient.backup_vault_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_backup_vault_path(path) + assert expected == actual + + +def test_binding_matching_resource_path(): + project = "winkle" + location = "nautilus" + auto_protection_policy = "scallop" + binding = "abalone" + matching_resource = "squid" + expected = "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + matching_resource=matching_resource, + ) + actual = BackupDRClient.binding_matching_resource_path( + project, location, auto_protection_policy, binding, matching_resource + ) + assert expected == actual + + +def test_parse_binding_matching_resource_path(): + expected = { + "project": "clam", + "location": "whelk", + "auto_protection_policy": "octopus", + "binding": "oyster", + "matching_resource": "nudibranch", + } + path = BackupDRClient.binding_matching_resource_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_binding_matching_resource_path(path) + assert expected == actual + + +def test_cluster_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format( + project=project, + location=location, + cluster=cluster, + ) + actual = BackupDRClient.cluster_path(project, location, cluster) + assert expected == actual + + +def test_parse_cluster_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "cluster": "abalone", + } + path = BackupDRClient.cluster_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_cluster_path(path) + assert expected == actual + + +def test_crypto_key_path(): + project = "squid" + location = "clam" + ring = "whelk" + key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{ring}/cryptoKeys/{key}".format( + project=project, + location=location, + ring=ring, + key=key, + ) + actual = BackupDRClient.crypto_key_path(project, location, ring, key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "ring": "cuttlefish", + "key": "mussel", + } + path = BackupDRClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_crypto_key_path(path) + assert expected == actual + + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + actual = BackupDRClient.crypto_key_version_path( + project, location, key_ring, crypto_key, crypto_key_version + ) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = BackupDRClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_crypto_key_version_path(path) + assert expected == actual + + +def test_data_source_path(): + project = "cuttlefish" + location = "mussel" + backupvault = "winkle" + datasource = "nautilus" + expected = "projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource}".format( + project=project, + location=location, + backupvault=backupvault, + datasource=datasource, + ) + actual = BackupDRClient.data_source_path(project, location, backupvault, datasource) + assert expected == actual + + +def test_parse_data_source_path(): + expected = { + "project": "scallop", + "location": "abalone", + "backupvault": "squid", + "datasource": "clam", + } + path = BackupDRClient.data_source_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_data_source_path(path) + assert expected == actual + + +def test_data_source_reference_path(): + project = "whelk" + location = "octopus" + data_source_reference = "oyster" + expected = "projects/{project}/locations/{location}/dataSourceReferences/{data_source_reference}".format( + project=project, + location=location, + data_source_reference=data_source_reference, + ) + actual = BackupDRClient.data_source_reference_path( + project, location, data_source_reference + ) + assert expected == actual + + +def test_parse_data_source_reference_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "data_source_reference": "mussel", + } + path = BackupDRClient.data_source_reference_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_data_source_reference_path(path) + assert expected == actual + + +def test_instance_path(): + project = "winkle" + instance = "nautilus" + expected = "projects/{project}/instances/{instance}".format( + project=project, + instance=instance, + ) + actual = BackupDRClient.instance_path(project, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "scallop", + "instance": "abalone", + } + path = BackupDRClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_instance_path(path) + assert expected == actual + + +def test_management_server_path(): + project = "squid" + location = "clam" + managementserver = "whelk" + expected = "projects/{project}/locations/{location}/managementServers/{managementserver}".format( + project=project, + location=location, + managementserver=managementserver, + ) + actual = BackupDRClient.management_server_path(project, location, managementserver) + assert expected == actual + + +def test_parse_management_server_path(): + expected = { + "project": "octopus", + "location": "oyster", + "managementserver": "nudibranch", + } + path = BackupDRClient.management_server_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_management_server_path(path) + assert expected == actual + + +def test_storage_pool_path(): + project = "cuttlefish" + zone = "mussel" + storage_pool = "winkle" + expected = "projects/{project}/zones/{zone}/storagePools/{storage_pool}".format( + project=project, + zone=zone, + storage_pool=storage_pool, + ) + actual = BackupDRClient.storage_pool_path(project, zone, storage_pool) + assert expected == actual + + +def test_parse_storage_pool_path(): + expected = { + "project": "nautilus", + "zone": "scallop", + "storage_pool": "abalone", + } + path = BackupDRClient.storage_pool_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_storage_pool_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = BackupDRClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = BackupDRClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = BackupDRClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = BackupDRClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = BackupDRClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = BackupDRClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = BackupDRClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = BackupDRClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = BackupDRClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = BackupDRClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.BackupDRTransport, "_prep_wrapped_messages" + ) as prep: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.BackupDRTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = BackupDRClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = BackupDRClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = BackupDRAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (BackupDRClient, transports.BackupDRGrpcTransport), + (BackupDRAsyncClient, transports.BackupDRGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr_protection_summary.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr_protection_summary.py new file mode 100644 index 000000000000..849069034660 --- /dev/null +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr_protection_summary.py @@ -0,0 +1,5245 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.backupdr_v1beta.services.backup_dr_protection_summary import ( + BackupDrProtectionSummaryAsyncClient, + BackupDrProtectionSummaryClient, + pagers, + transports, +) +from google.cloud.backupdr_v1beta.types import protection_summary + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert BackupDrProtectionSummaryClient._get_client_cert_source(None, False) is None + assert ( + BackupDrProtectionSummaryClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + BackupDrProtectionSummaryClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + BackupDrProtectionSummaryClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + BackupDrProtectionSummaryClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = BackupDrProtectionSummaryClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = BackupDrProtectionSummaryClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BackupDrProtectionSummaryClient, "grpc"), + (BackupDrProtectionSummaryAsyncClient, "grpc_asyncio"), + (BackupDrProtectionSummaryClient, "rest"), + ], +) +def test_backup_dr_protection_summary_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "backupdr.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.BackupDrProtectionSummaryGrpcTransport, "grpc"), + (transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BackupDrProtectionSummaryRestTransport, "rest"), + ], +) +def test_backup_dr_protection_summary_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BackupDrProtectionSummaryClient, "grpc"), + (BackupDrProtectionSummaryAsyncClient, "grpc_asyncio"), + (BackupDrProtectionSummaryClient, "rest"), + ], +) +def test_backup_dr_protection_summary_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "backupdr.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com" + ) + + +def test_backup_dr_protection_summary_client_get_transport_class(): + transport = BackupDrProtectionSummaryClient.get_transport_class() + available_transports = [ + transports.BackupDrProtectionSummaryGrpcTransport, + transports.BackupDrProtectionSummaryRestTransport, + ] + assert transport in available_transports + + transport = BackupDrProtectionSummaryClient.get_transport_class("grpc") + assert transport == transports.BackupDrProtectionSummaryGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryGrpcTransport, + "grpc", + ), + ( + BackupDrProtectionSummaryAsyncClient, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + BackupDrProtectionSummaryClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDrProtectionSummaryClient), +) +@mock.patch.object( + BackupDrProtectionSummaryAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDrProtectionSummaryAsyncClient), +) +def test_backup_dr_protection_summary_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + BackupDrProtectionSummaryClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + BackupDrProtectionSummaryClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryGrpcTransport, + "grpc", + "true", + ), + ( + BackupDrProtectionSummaryAsyncClient, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryGrpcTransport, + "grpc", + "false", + ), + ( + BackupDrProtectionSummaryAsyncClient, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryRestTransport, + "rest", + "true", + ), + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + BackupDrProtectionSummaryClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDrProtectionSummaryClient), +) +@mock.patch.object( + BackupDrProtectionSummaryAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDrProtectionSummaryAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_backup_dr_protection_summary_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [BackupDrProtectionSummaryClient, BackupDrProtectionSummaryAsyncClient], +) +@mock.patch.object( + BackupDrProtectionSummaryClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(BackupDrProtectionSummaryClient), +) +@mock.patch.object( + BackupDrProtectionSummaryAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(BackupDrProtectionSummaryAsyncClient), +) +def test_backup_dr_protection_summary_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", + [BackupDrProtectionSummaryClient, BackupDrProtectionSummaryAsyncClient], +) +@mock.patch.object( + BackupDrProtectionSummaryClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDrProtectionSummaryClient), +) +@mock.patch.object( + BackupDrProtectionSummaryAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BackupDrProtectionSummaryAsyncClient), +) +def test_backup_dr_protection_summary_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = BackupDrProtectionSummaryClient._DEFAULT_UNIVERSE + default_endpoint = ( + BackupDrProtectionSummaryClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = BackupDrProtectionSummaryClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryGrpcTransport, + "grpc", + ), + ( + BackupDrProtectionSummaryAsyncClient, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryRestTransport, + "rest", + ), + ], +) +def test_backup_dr_protection_summary_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + BackupDrProtectionSummaryAsyncClient, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryRestTransport, + "rest", + None, + ), + ], +) +def test_backup_dr_protection_summary_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_backup_dr_protection_summary_client_client_options_from_dict(): + with mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.transports.BackupDrProtectionSummaryGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = BackupDrProtectionSummaryClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + BackupDrProtectionSummaryAsyncClient, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_backup_dr_protection_summary_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "backupdr.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="backupdr.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + protection_summary.ListResourceBackupConfigsRequest(), + {}, + ], +) +def test_list_resource_backup_configs(request_type, transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = protection_summary.ListResourceBackupConfigsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_resource_backup_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = protection_summary.ListResourceBackupConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceBackupConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_resource_backup_configs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = protection_summary.ListResourceBackupConfigsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_resource_backup_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = protection_summary.ListResourceBackupConfigsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_resource_backup_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_resource_backup_configs + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_resource_backup_configs + ] = mock_rpc + request = {} + client.list_resource_backup_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_backup_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_resource_backup_configs_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_resource_backup_configs + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_resource_backup_configs + ] = mock_rpc + + request = {} + await client.list_resource_backup_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_resource_backup_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + protection_summary.ListResourceBackupConfigsRequest(), + {}, + ], +) +async def test_list_resource_backup_configs_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + protection_summary.ListResourceBackupConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_resource_backup_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = protection_summary.ListResourceBackupConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceBackupConfigsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_resource_backup_configs_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = protection_summary.ListResourceBackupConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + call.return_value = protection_summary.ListResourceBackupConfigsResponse() + client.list_resource_backup_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_resource_backup_configs_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = protection_summary.ListResourceBackupConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + protection_summary.ListResourceBackupConfigsResponse() + ) + await client.list_resource_backup_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_resource_backup_configs_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = protection_summary.ListResourceBackupConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_backup_configs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_resource_backup_configs_flattened_error(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_resource_backup_configs( + protection_summary.ListResourceBackupConfigsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_resource_backup_configs_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = protection_summary.ListResourceBackupConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + protection_summary.ListResourceBackupConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_backup_configs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_resource_backup_configs_flattened_error_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_resource_backup_configs( + protection_summary.ListResourceBackupConfigsRequest(), + parent="parent_value", + ) + + +def test_list_resource_backup_configs_pager(transport_name: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + next_page_token="abc", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[], + next_page_token="def", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + ], + next_page_token="ghi", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_resource_backup_configs( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, protection_summary.ResourceBackupConfig) for i in results + ) + + +def test_list_resource_backup_configs_pages(transport_name: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + next_page_token="abc", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[], + next_page_token="def", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + ], + next_page_token="ghi", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_backup_configs(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_resource_backup_configs_async_pager(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + next_page_token="abc", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[], + next_page_token="def", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + ], + next_page_token="ghi", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_backup_configs( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, protection_summary.ResourceBackupConfig) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_resource_backup_configs_async_pages(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + next_page_token="abc", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[], + next_page_token="def", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + ], + next_page_token="ghi", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_resource_backup_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_resource_backup_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_resource_backup_configs + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_resource_backup_configs + ] = mock_rpc + + request = {} + client.list_resource_backup_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_backup_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_resource_backup_configs_rest_required_fields( + request_type=protection_summary.ListResourceBackupConfigsRequest, +): + transport_class = transports.BackupDrProtectionSummaryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListResourceBackupConfigs, + "_BaseListResourceBackupConfigs__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = protection_summary.ListResourceBackupConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = protection_summary.ListResourceBackupConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_resource_backup_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_resource_backup_configs_rest_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = protection_summary.ListResourceBackupConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = protection_summary.ListResourceBackupConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_resource_backup_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/resourceBackupConfigs" + % client.transport._host, + args[1], + ) + + +def test_list_resource_backup_configs_rest_flattened_error(transport: str = "rest"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_resource_backup_configs( + protection_summary.ListResourceBackupConfigsRequest(), + parent="parent_value", + ) + + +def test_list_resource_backup_configs_rest_pager(transport: str = "rest"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + next_page_token="abc", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[], + next_page_token="def", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + ], + next_page_token="ghi", + ), + protection_summary.ListResourceBackupConfigsResponse( + resource_backup_configs=[ + protection_summary.ResourceBackupConfig(), + protection_summary.ResourceBackupConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + protection_summary.ListResourceBackupConfigsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_resource_backup_configs(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, protection_summary.ResourceBackupConfig) for i in results + ) + + pages = list(client.list_resource_backup_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BackupDrProtectionSummaryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BackupDrProtectionSummaryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDrProtectionSummaryClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BackupDrProtectionSummaryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BackupDrProtectionSummaryClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BackupDrProtectionSummaryClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BackupDrProtectionSummaryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDrProtectionSummaryClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDrProtectionSummaryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BackupDrProtectionSummaryClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDrProtectionSummaryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BackupDrProtectionSummaryGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDrProtectionSummaryGrpcTransport, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + transports.BackupDrProtectionSummaryRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = BackupDrProtectionSummaryClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_resource_backup_configs_empty_call_grpc(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + call.return_value = protection_summary.ListResourceBackupConfigsResponse() + client.list_resource_backup_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = protection_summary.ListResourceBackupConfigsRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BackupDrProtectionSummaryAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_resource_backup_configs_empty_call_grpc_asyncio(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + protection_summary.ListResourceBackupConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_resource_backup_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = protection_summary.ListResourceBackupConfigsRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BackupDrProtectionSummaryClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_resource_backup_configs_rest_bad_request( + request_type=protection_summary.ListResourceBackupConfigsRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_resource_backup_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + protection_summary.ListResourceBackupConfigsRequest, + dict, + ], +) +def test_list_resource_backup_configs_rest_call_success(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = protection_summary.ListResourceBackupConfigsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = protection_summary.ListResourceBackupConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_resource_backup_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceBackupConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_backup_configs_rest_interceptors(null_interceptor): + transport = transports.BackupDrProtectionSummaryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BackupDrProtectionSummaryRestInterceptor(), + ) + client = BackupDrProtectionSummaryClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDrProtectionSummaryRestInterceptor, + "post_list_resource_backup_configs", + ) as post, + mock.patch.object( + transports.BackupDrProtectionSummaryRestInterceptor, + "post_list_resource_backup_configs_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDrProtectionSummaryRestInterceptor, + "pre_list_resource_backup_configs", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = protection_summary.ListResourceBackupConfigsRequest.pb( + protection_summary.ListResourceBackupConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = protection_summary.ListResourceBackupConfigsResponse.to_json( + protection_summary.ListResourceBackupConfigsResponse() + ) + req.return_value.content = return_value + + request = protection_summary.ListResourceBackupConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = protection_summary.ListResourceBackupConfigsResponse() + post_with_metadata.return_value = ( + protection_summary.ListResourceBackupConfigsResponse(), + metadata, + ) + + client.list_resource_backup_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/managementServers/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/managementServers/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/managementServers/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/managementServers/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_resource_backup_configs_empty_call_rest(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_backup_configs), "__call__" + ) as call: + client.list_resource_backup_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = protection_summary.ListResourceBackupConfigsRequest() + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BackupDrProtectionSummaryGrpcTransport, + ) + + +def test_backup_dr_protection_summary_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BackupDrProtectionSummaryTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_backup_dr_protection_summary_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.transports.BackupDrProtectionSummaryTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.BackupDrProtectionSummaryTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_resource_backup_configs", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_backup_dr_protection_summary_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.transports.BackupDrProtectionSummaryTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BackupDrProtectionSummaryTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_backup_dr_protection_summary_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.backupdr_v1beta.services.backup_dr_protection_summary.transports.BackupDrProtectionSummaryTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BackupDrProtectionSummaryTransport() + adc.assert_called_once() + + +def test_backup_dr_protection_summary_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + BackupDrProtectionSummaryClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDrProtectionSummaryGrpcTransport, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + ], +) +def test_backup_dr_protection_summary_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDrProtectionSummaryGrpcTransport, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + transports.BackupDrProtectionSummaryRestTransport, + ], +) +def test_backup_dr_protection_summary_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.BackupDrProtectionSummaryGrpcTransport, grpc_helpers), + (transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_backup_dr_protection_summary_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "backupdr.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-backupdr", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="backupdr.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDrProtectionSummaryGrpcTransport, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + ], +) +def test_backup_dr_protection_summary_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_backup_dr_protection_summary_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.BackupDrProtectionSummaryRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_backup_dr_protection_summary_host_no_port(transport_name): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="backupdr.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "backupdr.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_backup_dr_protection_summary_host_with_port(transport_name): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="backupdr.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "backupdr.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://backupdr.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_backup_dr_protection_summary_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BackupDrProtectionSummaryClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BackupDrProtectionSummaryClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_resource_backup_configs._session + session2 = client2.transport.list_resource_backup_configs._session + assert session1 != session2 + + +def test_backup_dr_protection_summary_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BackupDrProtectionSummaryGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_backup_dr_protection_summary_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BackupDrProtectionSummaryGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDrProtectionSummaryGrpcTransport, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + ], +) +def test_backup_dr_protection_summary_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDrProtectionSummaryGrpcTransport, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + ], +) +def test_backup_dr_protection_summary_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_resource_backup_config_path(): + project = "squid" + location = "clam" + resource_backup_config = "whelk" + expected = "projects/{project}/locations/{location}/resourceBackupConfigs/{resource_backup_config}".format( + project=project, + location=location, + resource_backup_config=resource_backup_config, + ) + actual = BackupDrProtectionSummaryClient.resource_backup_config_path( + project, location, resource_backup_config + ) + assert expected == actual + + +def test_parse_resource_backup_config_path(): + expected = { + "project": "octopus", + "location": "oyster", + "resource_backup_config": "nudibranch", + } + path = BackupDrProtectionSummaryClient.resource_backup_config_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDrProtectionSummaryClient.parse_resource_backup_config_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = BackupDrProtectionSummaryClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = BackupDrProtectionSummaryClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDrProtectionSummaryClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = BackupDrProtectionSummaryClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = BackupDrProtectionSummaryClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDrProtectionSummaryClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = BackupDrProtectionSummaryClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = BackupDrProtectionSummaryClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDrProtectionSummaryClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = BackupDrProtectionSummaryClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = BackupDrProtectionSummaryClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDrProtectionSummaryClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = BackupDrProtectionSummaryClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = BackupDrProtectionSummaryClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDrProtectionSummaryClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.BackupDrProtectionSummaryTransport, "_prep_wrapped_messages" + ) as prep: + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.BackupDrProtectionSummaryTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = BackupDrProtectionSummaryClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = BackupDrProtectionSummaryAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = BackupDrProtectionSummaryClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + BackupDrProtectionSummaryClient, + transports.BackupDrProtectionSummaryGrpcTransport, + ), + ( + BackupDrProtectionSummaryAsyncClient, + transports.BackupDrProtectionSummaryGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_compat.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_compat.py new file mode 100644 index 000000000000..8466c827ff47 --- /dev/null +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_compat.py @@ -0,0 +1,429 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Tests for the compatibility module for older versions of google-api-core.""" + +import json +import os +from unittest import mock + +import google.auth.transport.mtls +import pytest +from google.api_core.universe import EmptyUniverseError +from google.auth.exceptions import MutualTLSChannelError +from google.protobuf import descriptor_pb2 + +from google.cloud.backupdr_v1beta._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, + transcode_request, +) + + +def test_get_universe_domain(): + # When universe_domain is provided + assert get_universe_domain("foo.com", default_universe="default.com") == "foo.com" + assert ( + get_universe_domain(" foo.com ", default_universe="default.com") == "foo.com" + ) + + # When universe_domain is None, falls back to default_universe + assert get_universe_domain(None, default_universe="default.com") == "default.com" + + # When multiple potential universes are provided, resolves in order of preference + assert ( + get_universe_domain("foo.com", "bar.com", default_universe="default.com") + == "foo.com" + ) + assert ( + get_universe_domain(None, "bar.com", default_universe="default.com") + == "bar.com" + ) + assert ( + get_universe_domain(None, None, default_universe="default.com") == "default.com" + ) + + # EmptyUniverseError raised when resolved value is empty string + with pytest.raises(EmptyUniverseError) as excinfo: + get_universe_domain("", default_universe="default.com") + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + with pytest.raises(EmptyUniverseError) as excinfo: + get_universe_domain(" ", default_universe="default.com") + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + with pytest.raises(EmptyUniverseError) as excinfo: + get_universe_domain(None, "", default_universe="default.com") + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +def test_get_default_mtls_endpoint(): + # Test valid API endpoints + assert get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" + assert ( + get_default_mtls_endpoint("foo.sandbox.googleapis.com") + == "foo.mtls.sandbox.googleapis.com" + ) + # Test case-insensitivity + assert get_default_mtls_endpoint("foo.GoogleAPIs.com") == "foo.mtls.googleapis.com" + assert ( + get_default_mtls_endpoint("foo.Sandbox.GoogleAPIs.com") + == "foo.mtls.sandbox.googleapis.com" + ) + + # Test valid API endpoints with schemes + assert ( + get_default_mtls_endpoint("https://foo.googleapis.com") + == "https://foo.mtls.googleapis.com" + ) + assert ( + get_default_mtls_endpoint("http://foo.googleapis.com:8080/v1") + == "http://foo.mtls.googleapis.com:8080/v1" + ) + + # Test valid API endpoints with ports + assert ( + get_default_mtls_endpoint("foo.googleapis.com:443") + == "foo.mtls.googleapis.com:443" + ) + assert ( + get_default_mtls_endpoint("foo.sandbox.googleapis.com:443") + == "foo.mtls.sandbox.googleapis.com:443" + ) + # Test case-insensitivity with ports + assert ( + get_default_mtls_endpoint("foo.GoogleAPIs.com:443") + == "foo.mtls.googleapis.com:443" + ) + assert ( + get_default_mtls_endpoint("foo.Sandbox.GoogleAPIs.com:443") + == "foo.mtls.sandbox.googleapis.com:443" + ) + + # Test endpoints that shouldn't be converted + assert ( + get_default_mtls_endpoint("foo.mtls.googleapis.com") + == "foo.mtls.googleapis.com" + ) + assert get_default_mtls_endpoint("foo.com") == "foo.com" + assert get_default_mtls_endpoint("foo.com:8080") == "foo.com:8080" + + # Test empty/None endpoints + assert get_default_mtls_endpoint("") == "" + assert get_default_mtls_endpoint(None) is None + + # Test endpoints without host + assert get_default_mtls_endpoint("http://") == "http://" + assert get_default_mtls_endpoint("https://") == "https://" + + +@pytest.mark.parametrize( + "api_override,universe_domain,default_universe,default_mtls_endpoint,default_endpoint_template,use_mtls,expected", + [ + ( + "foo.com", + "googleapis.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + True, + "foo.com", + ), + ( + None, + "googleapis.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + True, + "foo.mtls.googleapis.com", + ), + ( + None, + "googleapis.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + False, + "foo.googleapis.com", + ), + ( + None, + "bar.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + True, + MutualTLSChannelError, + ), + ( + None, + "googleapis.com", + "googleapis.com", + None, + "foo.{UNIVERSE_DOMAIN}", + True, + ValueError, + ), + ], +) +def test_get_api_endpoint( + api_override, + universe_domain, + default_universe, + default_mtls_endpoint, + default_endpoint_template, + use_mtls, + expected, +): + if isinstance(expected, type) and issubclass(expected, Exception): + with pytest.raises(expected): + get_api_endpoint( + api_override, + universe_domain, + default_universe, + default_mtls_endpoint, + default_endpoint_template, + use_mtls, + ) + else: + assert ( + get_api_endpoint( + api_override, + universe_domain, + default_universe, + default_mtls_endpoint, + default_endpoint_template, + use_mtls, + ) + == expected + ) + + +def test_should_use_client_cert_fallback_env(): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}, clear=True + ): + assert should_use_client_cert() is True + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}, clear=True + ): + assert should_use_client_cert() is False + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"}, clear=True + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises( + ValueError, + match="Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`", + ): + should_use_client_cert() + + +def test_transcode_basic(): + # We use FieldDescriptorProto as it has standard primitive fields and nested messages. + http_options = [ + { + "method": "get", + "uri": "/v1/test/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.number = 123 + + transcoded, body, query_params = transcode_request(http_options, request) + + assert transcoded["method"] == "get" + assert transcoded["uri"] == "/v1/test/my-field" + assert body is None + # 'number' should be in query parameters + assert "number" in query_params + assert query_params["number"] == 123 + + +def test_transcode_with_nested_field(): + http_options = [ + { + "method": "get", + "uri": "/v1/test/{options.deprecated}/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.options.deprecated = True + request.number = 123 + + transcoded, body, query_params = transcode_request(http_options, request) + + assert transcoded["method"] == "get" + assert transcoded["uri"] == "/v1/test/True/my-field" + assert body is None + assert "number" in query_params + assert query_params["number"] == 123 + + +def test_transcode_with_body(): + http_options = [ + { + "method": "post", + "uri": "/v1/test/{name}", + "body": "options", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.options.deprecated = True + request.number = 123 + + transcoded, body, query_params = transcode_request(http_options, request) + + assert transcoded["method"] == "post" + assert transcoded["uri"] == "/v1/test/my-field" + assert body is not None + body_data = json.loads(body) + assert body_data["deprecated"] is True + # Query parameters should not contain 'options' (the body) + assert "number" in query_params + assert query_params["number"] == 123 + assert "options" not in query_params + + +def test_transcode_with_required_fields_default_values(): + http_options = [ + { + "method": "get", + "uri": "/v1/test/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + + required_defaults = {"requiredQueryParam": "default-val"} + + transcoded, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=required_defaults, + ) + + assert query_params["requiredQueryParam"] == "default-val" + + +def test_transcode_with_numeric_enums(): + http_options = [ + { + "method": "get", + "uri": "/v1/test/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.type = descriptor_pb2.FieldDescriptorProto.TYPE_STRING + + # Without numeric enums + _, _, query_params = transcode_request( + http_options, request, rest_numeric_enums=False + ) + assert query_params["type"] == "TYPE_STRING" + + # With numeric enums + _, _, query_params = transcode_request( + http_options, request, rest_numeric_enums=True + ) + # Type number for TYPE_STRING is 9 + assert query_params["type"] == 9 + assert query_params["$alt"] == "json;enum-encoding=int" + + +def test_transcode_no_query_params(): + http_options = [{"method": "get", "uri": "/v1/test"}] + request = descriptor_pb2.FieldDescriptorProto() + + with mock.patch( + "google.api_core.path_template.transcode", + return_value={"method": "get", "uri": "/v1/test"}, + ): + transcoded, body, query_params = transcode_request(http_options, request) + assert query_params == {} + + +def test_transcode_with_required_fields_existing_key(): + http_options = [ + { + "method": "get", + "uri": "/v1/test", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "custom-name" + + required_defaults = {"name": "default-name"} + + transcoded, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=required_defaults, + ) + + assert query_params["name"] == "custom-name" + + +def test_transcode_request_invalid_request(): + http_options = [{"method": "get", "uri": "/v1/test"}] + with pytest.raises(TypeError, match="request cannot be None"): + transcode_request(http_options, None) + + +def test_transcode_request_proto_plus_wrapper(): + http_options = [{"method": "get", "uri": "/v1/test/{name}"}] + mock_pb = descriptor_pb2.FieldDescriptorProto() + mock_pb.name = "proto-plus-field" + + mock_proto_plus = mock.Mock() + mock_proto_plus._pb = mock_pb + + transcoded, _, _ = transcode_request(http_options, mock_proto_plus) + assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_read_environment_variables(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "true", + "GOOGLE_API_USE_MTLS_ENDPOINT": "always", + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com", + }, + ): + use_cert, mtls_endpoint, universe_domain = read_environment_variables() + assert use_cert is True + assert mtls_endpoint == "always" + assert universe_domain == "foo.com" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): + with pytest.raises(MutualTLSChannelError): + read_environment_variables() diff --git a/packages/google-cloud-bigquery/CHANGELOG.md b/packages/google-cloud-bigquery/CHANGELOG.md index f8b64e97845b..744de8fdca65 100644 --- a/packages/google-cloud-bigquery/CHANGELOG.md +++ b/packages/google-cloud-bigquery/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-bigquery/#history +## [3.45.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-v3.45.1...google-cloud-bigquery-v3.45.2) (2026-09-17) + + +### Bug Fixes + +* disambiguate google-cloud-bigquery `to_dataframe` usage from `pandas-gbq` in ua. ([#18369](https://github.com/googleapis/google-cloud-python/issues/18369)) ([0d7d59c](https://github.com/googleapis/google-cloud-python/commit/0d7d59c771ce1b0084cb8c18e4713f37dc73821d)) + ## [3.45.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-v3.45.0...google-cloud-bigquery-v3.45.1) (2026-09-14) diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py index 07fec2fc0fa9..e1cb5e1bdcdf 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py @@ -78,6 +78,9 @@ job, ) from google.cloud.bigquery import exceptions as bq_exceptions +from google.cloud.bigquery import ( + version as bq_version, +) from google.cloud.bigquery._helpers import ( _DEFAULT_HOST, _DEFAULT_HOST_TEMPLATE, @@ -148,7 +151,7 @@ _RESUMABLE_URL_TEMPLATE = _BASE_UPLOAD_TEMPLATE + "resumable" _GENERIC_CONTENT_TYPE = "*/*" _READ_LESS_THAN_SIZE = ( - "Size {:d} was specified but the file-like object only had " "{:d} bytes remaining." + "Size {:d} was specified but the file-like object only had {:d} bytes remaining." ) _NEED_TABLE_ARGUMENT = ( "The table argument should be a table ID string, Table, or TableReference" @@ -641,9 +644,16 @@ def _ensure_bqstorage_client( pandas_gbq = None # type: ignore if pandas_gbq is None: - user_agent = "pandas-gbq/0.0.0" + # Even if pandas-gbq isn't installed, attribute all + # to_dataframe/to_arrow usage the same as we do the recommended + # (pandas-gbq) code paths. + pandas_user_agent = "pandas-gbq/0.0.0" else: - user_agent = f"pandas-gbq/{pandas_gbq.__version__}" + pandas_user_agent = f"pandas-gbq/{pandas_gbq.__version__}" + + # Track the google-cloud-bigquery version as "legacy" because this code + # path is intended to be migrated to pandas-gbq itself. + user_agent = f"legacy-gcb/{bq_version.__version__} {pandas_user_agent}" if client_info is None: amended_client_info = google.api_core.gapic_v1.client_info.ClientInfo( diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/version.py b/packages/google-cloud-bigquery/google/cloud/bigquery/version.py index 557f08de8b1b..6993d2ceea34 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/version.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "3.45.1" +__version__ = "3.45.2" diff --git a/packages/google-cloud-bigquery/noxfile.py b/packages/google-cloud-bigquery/noxfile.py index 5dfe419fedf2..c366a50e293f 100644 --- a/packages/google-cloud-bigquery/noxfile.py +++ b/packages/google-cloud-bigquery/noxfile.py @@ -15,12 +15,12 @@ from __future__ import absolute_import import contextlib +from functools import wraps import os import pathlib import re import shutil import time -from functools import wraps from typing import Generator import nox diff --git a/packages/google-cloud-bigquery/tests/unit/test_client.py b/packages/google-cloud-bigquery/tests/unit/test_client.py index 5cce574d3ff1..c48a73cc2ebd 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_client.py +++ b/packages/google-cloud-bigquery/tests/unit/test_client.py @@ -54,7 +54,7 @@ import google.cloud.bigquery.table from google.api_core import client_info from google.cloud import bigquery -from google.cloud.bigquery import ParquetOptions, exceptions +from google.cloud.bigquery import ParquetOptions, exceptions, version from google.cloud.bigquery.dataset import Dataset, DatasetReference from google.cloud.bigquery.enums import DatasetView, TimestampPrecision, UpdateMode from google.cloud.bigquery.retry import DEFAULT_TIMEOUT @@ -840,6 +840,9 @@ def test_ensure_bqstorage_client_creating_new_instance(self): self.assertIs(kwargs["client_options"], mock.sentinel.client_options) self.assertIn("test-agent", kwargs["client_info"].user_agent) self.assertIn("pandas-gbq", kwargs["client_info"].user_agent) + self.assertIn( + f"legacy-gcb/{version.__version__}", kwargs["client_info"].user_agent + ) def test_ensure_bqstorage_client_pandas_gbq_installed(self): bigquery_storage = pytest.importorskip("google.cloud.bigquery_storage") @@ -857,15 +860,17 @@ def test_ensure_bqstorage_client_pandas_gbq_installed(self): mock_pandas = mock.Mock() mock_pandas.__version__ = "0.13.0" - with mock.patch( - "google.cloud.bigquery_storage.BigQueryReadClient", mock_client - ), mock.patch.dict(sys.modules, {"pandas_gbq": mock_pandas}): + with ( + mock.patch("google.cloud.bigquery_storage.BigQueryReadClient", mock_client), + mock.patch.dict(sys.modules, {"pandas_gbq": mock_pandas}), + ): client._ensure_bqstorage_client(client_info=client_info) mock_client.assert_called_once() _, kwargs = mock_client.call_args self.assertEqual( - kwargs["client_info"].user_agent, "app-agent pandas-gbq/0.13.0" + kwargs["client_info"].user_agent, + f"app-agent legacy-gcb/{version.__version__} pandas-gbq/0.13.0", ) def test_ensure_bqstorage_client_pandas_gbq_not_installed(self): @@ -881,14 +886,18 @@ def test_ensure_bqstorage_client_pandas_gbq_not_installed(self): user_agent="app-agent" ) - with mock.patch( - "google.cloud.bigquery_storage.BigQueryReadClient", mock_client - ), mock.patch.dict(sys.modules, {"pandas_gbq": None}): + with ( + mock.patch("google.cloud.bigquery_storage.BigQueryReadClient", mock_client), + mock.patch.dict(sys.modules, {"pandas_gbq": None}), + ): client._ensure_bqstorage_client(client_info=client_info) mock_client.assert_called_once() _, kwargs = mock_client.call_args - self.assertEqual(kwargs["client_info"].user_agent, "app-agent pandas-gbq/0.0.0") + self.assertEqual( + kwargs["client_info"].user_agent, + f"app-agent legacy-gcb/{version.__version__} pandas-gbq/0.0.0", + ) def test_ensure_bqstorage_client_client_info_none(self): bigquery_storage = pytest.importorskip("google.cloud.bigquery_storage") @@ -898,14 +907,18 @@ def test_ensure_bqstorage_client_client_info_none(self): creds = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=creds) - with mock.patch( - "google.cloud.bigquery_storage.BigQueryReadClient", mock_client - ), mock.patch.dict(sys.modules, {"pandas_gbq": None}): + with ( + mock.patch("google.cloud.bigquery_storage.BigQueryReadClient", mock_client), + mock.patch.dict(sys.modules, {"pandas_gbq": None}), + ): client._ensure_bqstorage_client(client_info=None) mock_client.assert_called_once() _, kwargs = mock_client.call_args - self.assertEqual(kwargs["client_info"].user_agent, "pandas-gbq/0.0.0") + self.assertEqual( + kwargs["client_info"].user_agent, + f"legacy-gcb/{version.__version__} pandas-gbq/0.0.0", + ) def test_ensure_bqstorage_client_client_info_user_agent_none(self): bigquery_storage = pytest.importorskip("google.cloud.bigquery_storage") @@ -919,14 +932,18 @@ def test_ensure_bqstorage_client_client_info_user_agent_none(self): client_info = google.api_core.gapic_v1.client_info.ClientInfo(user_agent=None) - with mock.patch( - "google.cloud.bigquery_storage.BigQueryReadClient", mock_client - ), mock.patch.dict(sys.modules, {"pandas_gbq": None}): + with ( + mock.patch("google.cloud.bigquery_storage.BigQueryReadClient", mock_client), + mock.patch.dict(sys.modules, {"pandas_gbq": None}), + ): client._ensure_bqstorage_client(client_info=client_info) mock_client.assert_called_once() _, kwargs = mock_client.call_args - self.assertEqual(kwargs["client_info"].user_agent, "pandas-gbq/0.0.0") + self.assertEqual( + kwargs["client_info"].user_agent, + f"legacy-gcb/{version.__version__} pandas-gbq/0.0.0", + ) def test_ensure_bqstorage_client_missing_dependency(self): creds = _make_credentials() @@ -9157,9 +9174,10 @@ def test_load_table_from_dataframe_w_partial_schema_extra_types(self): SchemaField("unknown_col", "BYTES"), ) job_config = job.LoadJobConfig(schema=schema) - with load_patch as load_table_from_file, pytest.raises( - ValueError - ) as exc_context: + with ( + load_patch as load_table_from_file, + pytest.raises(ValueError) as exc_context, + ): client.load_table_from_dataframe( dataframe, self.TABLE_REF, job_config=job_config, location=self.LOCATION ) @@ -9429,9 +9447,13 @@ def test_load_table_from_dataframe_emits_pending_deprecation_warning(self): get_table_patch = mock.patch( "google.cloud.bigquery.client.Client.get_table", autospec=True ) - with load_patch, get_table_patch, pytest.warns( - PendingDeprecationWarning, - match="Loading DataFrames via google-cloud-bigquery is deprecated", + with ( + load_patch, + get_table_patch, + pytest.warns( + PendingDeprecationWarning, + match="Loading DataFrames via google-cloud-bigquery is deprecated", + ), ): client.load_table_from_dataframe(dataframe, self.TABLE_REF) @@ -9853,7 +9875,7 @@ def test_load_table_from_json_unicode_emoji_data_case(self): client = self._make_client() - emoji = "\U0001F3E6" + emoji = "\U0001f3e6" json_row = {"emoji": emoji} json_rows = [json_row] diff --git a/packages/google-cloud-bigquery/tests/unit/test_table.py b/packages/google-cloud-bigquery/tests/unit/test_table.py index ed4fc2bda867..31556cb2b4fa 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_table.py +++ b/packages/google-cloud-bigquery/tests/unit/test_table.py @@ -16,6 +16,7 @@ import datetime import logging import re +import sys import time import types import unittest @@ -376,9 +377,7 @@ def test_from_api_repr(self): def test___repr__(self): dataset = DatasetReference("project1", "dataset1") table1 = self._make_one(dataset, "table1") - expected = ( - "TableReference(DatasetReference('project1', 'dataset1'), " "'table1')" - ) + expected = "TableReference(DatasetReference('project1', 'dataset1'), 'table1')" self.assertEqual(repr(table1), expected) def test___str__(self): @@ -1831,9 +1830,7 @@ def test___repr__(self): dataset = DatasetReference("project1", "dataset1") table1 = self._make_one(TableReference(dataset, "table1")) expected = ( - "Table(TableReference(" - "DatasetReference('project1', 'dataset1'), " - "'table1'))" + "Table(TableReference(DatasetReference('project1', 'dataset1'), 'table1'))" ) self.assertEqual(repr(table1), expected) @@ -2893,7 +2890,8 @@ def test__should_use_bqstorage_returns_true_if_no_cached_results(self): def test__should_use_bqstorage_returns_false_if_page_token_set(self): iterator = self._make_one( - page_token="abc", first_page_response=None # not cached + page_token="abc", + first_page_response=None, # not cached ) result = iterator._should_use_bqstorage( bqstorage_client=None, create_bqstorage_client=True @@ -2902,7 +2900,8 @@ def test__should_use_bqstorage_returns_false_if_page_token_set(self): def test__should_use_bqstorage_returns_false_if_max_results_set(self): iterator = self._make_one( - max_results=10, first_page_response=None # not cached + max_results=10, + first_page_response=None, # not cached ) result = iterator._should_use_bqstorage( bqstorage_client=None, create_bqstorage_client=True @@ -3548,6 +3547,117 @@ def test_to_arrow_w_bqstorage_creates_client(self): mock_client._ensure_bqstorage_client.assert_called_once() bqstorage_client._transport.close.assert_called_once() + def test_to_arrow_create_read_session_user_agent(self): + pytest.importorskip("numpy") + pytest.importorskip("pyarrow") + pytest.importorskip("google.cloud.bigquery_storage") + import google.auth.credentials + from google.cloud import bigquery_storage + from google.cloud.bigquery import client as client_module + from google.cloud.bigquery import schema, version + from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) + + mock_channel = mock.MagicMock() + mock_unary = mock.MagicMock() + mock_channel.unary_unary.return_value = mock_unary + mock_session = bigquery_storage.types.ReadSession( + name="projects/proj/locations/us/sessions/s1", + streams=[], + ) + mock_unary.with_call.return_value = (mock_session, mock.MagicMock()) + + mock_pandas_gbq = mock.Mock() + mock_pandas_gbq.__version__ = "0.13.0" + + with ( + mock.patch.object( + big_query_read_grpc_transport.BigQueryReadGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.dict(sys.modules, {"pandas_gbq": mock_pandas_gbq}), + ): + client = client_module.Client( + project="proj", + credentials=mock.Mock(spec=google.auth.credentials.Credentials), + ) + row_iterator = mut.RowIterator( + client, + None, # api_request: ignored + None, # path: ignored + [schema.SchemaField("colA", "STRING")], + table=mut.TableReference.from_string("proj.dset.tbl"), + total_rows=0, + ) + row_iterator.to_arrow(create_bqstorage_client=True) + + mock_unary.with_call.assert_called_once() + _, kwargs = mock_unary.with_call.call_args + metadata_dict = dict(kwargs["metadata"]) + self.assertIn("x-goog-api-client", metadata_dict) + user_agent = metadata_dict["x-goog-api-client"] + self.assertIn( + f"legacy-gcb/{version.__version__} pandas-gbq/0.13.0", + user_agent, + ) + + def test_to_arrow_create_read_session_user_agent_pandas_gbq_not_installed(self): + pytest.importorskip("numpy") + pytest.importorskip("pyarrow") + pytest.importorskip("google.cloud.bigquery_storage") + import google.auth.credentials + from google.cloud import bigquery_storage + from google.cloud.bigquery import client as client_module + from google.cloud.bigquery import schema, version + from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) + + mock_channel = mock.MagicMock() + mock_unary = mock.MagicMock() + mock_channel.unary_unary.return_value = mock_unary + mock_session = bigquery_storage.types.ReadSession( + name="projects/proj/locations/us/sessions/s1", + streams=[], + ) + mock_unary.with_call.return_value = (mock_session, mock.MagicMock()) + + with ( + mock.patch.object( + big_query_read_grpc_transport.BigQueryReadGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.dict(sys.modules, {"pandas_gbq": None}), + ): + client = client_module.Client( + project="proj", + credentials=mock.Mock(spec=google.auth.credentials.Credentials), + ) + row_iterator = mut.RowIterator( + client, + None, # api_request: ignored + None, # path: ignored + [schema.SchemaField("colA", "STRING")], + table=mut.TableReference.from_string("proj.dset.tbl"), + total_rows=0, + ) + row_iterator.to_arrow(create_bqstorage_client=True) + + mock_unary.with_call.assert_called_once() + _, kwargs = mock_unary.with_call.call_args + metadata_dict = dict(kwargs["metadata"]) + self.assertIn("x-goog-api-client", metadata_dict) + user_agent = metadata_dict["x-goog-api-client"] + self.assertIn( + f"legacy-gcb/{version.__version__} pandas-gbq/0.0.0", + user_agent, + ) + def test_to_arrow_ensure_bqstorage_client_wo_bqstorage(self): pytest.importorskip("numpy") pyarrow = pytest.importorskip( @@ -4903,6 +5013,117 @@ def test_to_dataframe_w_bqstorage_creates_client(self): mock_client._ensure_bqstorage_client.assert_called_once() bqstorage_client._transport.close.assert_called_once() + def test_to_dataframe_create_read_session_user_agent(self): + pytest.importorskip("numpy") + pytest.importorskip("pandas") + pytest.importorskip("google.cloud.bigquery_storage") + import google.auth.credentials + from google.cloud import bigquery_storage + from google.cloud.bigquery import client as client_module + from google.cloud.bigquery import schema, version + from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) + + mock_channel = mock.MagicMock() + mock_unary = mock.MagicMock() + mock_channel.unary_unary.return_value = mock_unary + mock_session = bigquery_storage.types.ReadSession( + name="projects/proj/locations/us/sessions/s1", + streams=[], + ) + mock_unary.with_call.return_value = (mock_session, mock.MagicMock()) + + mock_pandas_gbq = mock.Mock() + mock_pandas_gbq.__version__ = "0.13.0" + + with ( + mock.patch.object( + big_query_read_grpc_transport.BigQueryReadGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.dict(sys.modules, {"pandas_gbq": mock_pandas_gbq}), + ): + client = client_module.Client( + project="proj", + credentials=mock.Mock(spec=google.auth.credentials.Credentials), + ) + row_iterator = mut.RowIterator( + client, + None, # api_request: ignored + None, # path: ignored + [schema.SchemaField("colA", "STRING")], + table=mut.TableReference.from_string("proj.dset.tbl"), + total_rows=0, + ) + row_iterator.to_dataframe(create_bqstorage_client=True) + + mock_unary.with_call.assert_called_once() + _, kwargs = mock_unary.with_call.call_args + metadata_dict = dict(kwargs["metadata"]) + self.assertIn("x-goog-api-client", metadata_dict) + user_agent = metadata_dict["x-goog-api-client"] + self.assertIn( + f"legacy-gcb/{version.__version__} pandas-gbq/0.13.0", + user_agent, + ) + + def test_to_dataframe_create_read_session_user_agent_pandas_gbq_not_installed(self): + pytest.importorskip("numpy") + pytest.importorskip("pandas") + pytest.importorskip("google.cloud.bigquery_storage") + import google.auth.credentials + from google.cloud import bigquery_storage + from google.cloud.bigquery import client as client_module + from google.cloud.bigquery import schema, version + from google.cloud.bigquery import table as mut + from google.cloud.bigquery_storage_v1.services.big_query_read.transports import ( + grpc as big_query_read_grpc_transport, + ) + + mock_channel = mock.MagicMock() + mock_unary = mock.MagicMock() + mock_channel.unary_unary.return_value = mock_unary + mock_session = bigquery_storage.types.ReadSession( + name="projects/proj/locations/us/sessions/s1", + streams=[], + ) + mock_unary.with_call.return_value = (mock_session, mock.MagicMock()) + + with ( + mock.patch.object( + big_query_read_grpc_transport.BigQueryReadGrpcTransport, + "create_channel", + return_value=mock_channel, + ), + mock.patch.dict(sys.modules, {"pandas_gbq": None}), + ): + client = client_module.Client( + project="proj", + credentials=mock.Mock(spec=google.auth.credentials.Credentials), + ) + row_iterator = mut.RowIterator( + client, + None, # api_request: ignored + None, # path: ignored + [schema.SchemaField("colA", "STRING")], + table=mut.TableReference.from_string("proj.dset.tbl"), + total_rows=0, + ) + row_iterator.to_dataframe(create_bqstorage_client=True) + + mock_unary.with_call.assert_called_once() + _, kwargs = mock_unary.with_call.call_args + metadata_dict = dict(kwargs["metadata"]) + self.assertIn("x-goog-api-client", metadata_dict) + user_agent = metadata_dict["x-goog-api-client"] + self.assertIn( + f"legacy-gcb/{version.__version__} pandas-gbq/0.0.0", + user_agent, + ) + def test_to_dataframe_w_bqstorage_no_streams(self): pytest.importorskip("numpy") pytest.importorskip("pandas") @@ -5622,8 +5843,7 @@ def test_to_geodataframe_no_geog(self): with self.assertRaisesRegex( TypeError, re.escape( - "There must be at least one GEOGRAPHY column" - " to create a GeoDataFrame" + "There must be at least one GEOGRAPHY column to create a GeoDataFrame" ), ): row_iterator.to_geodataframe(create_bqstorage_client=False) diff --git a/packages/google-cloud-bigtable/CHANGELOG.md b/packages/google-cloud-bigtable/CHANGELOG.md index 51408bfccf08..4c319dab3848 100644 --- a/packages/google-cloud-bigtable/CHANGELOG.md +++ b/packages/google-cloud-bigtable/CHANGELOG.md @@ -4,6 +4,21 @@ [1]: https://pypi.org/project/google-cloud-bigtable/#history +## [2.46.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigtable-v2.45.0...google-cloud-bigtable-v2.46.0) (2026-09-17) + + +### Features + +* **bigtable:** Rerouted RowSet and RowRange to use ReadRows from data client ([#18196](https://github.com/googleapis/google-cloud-python/issues/18196)) ([1857302](https://github.com/googleapis/google-cloud-python/commit/1857302d5c602087b9a782c62694c33013eb77ea)) +* Rerouted ReadRows to data client ([#18198](https://github.com/googleapis/google-cloud-python/issues/18198)) ([934cd2d](https://github.com/googleapis/google-cloud-python/commit/934cd2da82be8b835192baa222e3a2ab5aa4b8d1)) +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + + +### Bug Fixes + +* **bigtable:** Added rst_stream exception handling for ReadRows. ([#18197](https://github.com/googleapis/google-cloud-python/issues/18197)) ([f30df60](https://github.com/googleapis/google-cloud-python/commit/f30df60eda27810cec277663dff532a158c999f3)) + ## [2.45.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigtable-v2.44.0...google-cloud-bigtable-v2.45.0) (2026-09-14) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/_read_rows.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/_read_rows.py index 9244d9cf193e..3e6c2b533b1e 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/_read_rows.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_async/_read_rows.py @@ -18,12 +18,12 @@ import time from typing import TYPE_CHECKING, Sequence -from google.api_core import retry as retries from grpc import StatusCode from google.cloud.bigtable.data._cross_sync import CrossSync from google.cloud.bigtable.data._helpers import ( _attempt_timeout_generator, + _rst_stream_aware_predicate, ) from google.cloud.bigtable.data._metrics.tracked_retry import tracked_retry from google.cloud.bigtable.data.exceptions import ( @@ -108,7 +108,7 @@ def __init__( else: self.request = query._to_pb(target) self.target = target - self._predicate = retries.if_exception_type(*retryable_exceptions) + self._predicate = _rst_stream_aware_predicate(*retryable_exceptions) self._last_yielded_row_key: bytes | None = None self._remaining_count: int | None = self.request.rows_limit or None self._operation_metric = metric diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py index c21b50064a6d..c13d7a8ae772 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_helpers.py @@ -20,9 +20,17 @@ import enum import time from collections import namedtuple -from typing import TYPE_CHECKING, List, Sequence, Tuple, Union +from typing import ( + TYPE_CHECKING, + Callable, + List, + Sequence, + Tuple, + Union, +) from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries from google.api_core.retry import RetryFailureReason, exponential_sleep_generator from google.cloud.bigtable.data.exceptions import RetryExceptionGroup @@ -50,6 +58,15 @@ # used by every data client as a default project name for testing on Bigtable emulator. _DEFAULT_BIGTABLE_EMULATOR_CLIENT = "google-cloud-bigtable-emulator" +# Internal error messages that can be retried during ReadRows. Internal error messages with this error +# text should be treated as Unavailable error messages with the same error text, and will therefore be +# treated as Unavailable errors rather than Internal errors. +_RETRYABLE_INTERNAL_ERROR_MESSAGES = ( + "rst_stream", + "rst stream", + "received unexpected eos on data frame from server", +) + # used to identify an active bigtable resource that needs to be warmed through PingAndWarm # each instance/app_profile_id pair needs to be individually tracked _WarmedInstanceKey = namedtuple( @@ -126,6 +143,36 @@ def _retry_exception_factory( return source_exc, cause_exc +def _rst_stream_aware_predicate( + *exception_types: type[Exception], +) -> Callable[[Exception], bool]: + """A custom retry predicate. + + This predicate treats Internal error messages with RST_STREAM errors as + ServiceUnavailable errors and will retry them if the Unavailable exception is retryable. + + Args: + exception_types: Exception types to be retried during operation + + Returns: + Callable[[Exception], bool]: A retry predicate that takes in an exception and + returns whether or not that exception is retryable + """ + # predicate to check for retryable error types + if_exception_type = retries.if_exception_type(*exception_types) + + # special case: treat InternalServerError with rst_stream error message as ServiceUnavailable + def rst_check(e): + return ( + core_exceptions.ServiceUnavailable in exception_types + and isinstance(e, core_exceptions.InternalServerError) + and isinstance(e.message, str) + and any(m in e.message.lower() for m in _RETRYABLE_INTERNAL_ERROR_MESSAGES) + ) + + return lambda e: if_exception_type(e) or rst_check(e) + + def _get_timeouts( operation: float | TABLE_DEFAULT, attempt: float | None | TABLE_DEFAULT, diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/_read_rows.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/_read_rows.py index 3c2f99283789..ce29226cac53 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/_read_rows.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/data/_sync_autogen/_read_rows.py @@ -21,11 +21,13 @@ import time from typing import TYPE_CHECKING, Sequence -from google.api_core import retry as retries from grpc import StatusCode from google.cloud.bigtable.data._cross_sync import CrossSync -from google.cloud.bigtable.data._helpers import _attempt_timeout_generator +from google.cloud.bigtable.data._helpers import ( + _attempt_timeout_generator, + _rst_stream_aware_predicate, +) from google.cloud.bigtable.data._metrics.tracked_retry import tracked_retry from google.cloud.bigtable.data.exceptions import ( InvalidChunk, @@ -98,7 +100,7 @@ def __init__( else: self.request = query._to_pb(target) self.target = target - self._predicate = retries.if_exception_type(*retryable_exceptions) + self._predicate = _rst_stream_aware_predicate(*retryable_exceptions) self._last_yielded_row_key: bytes | None = None self._remaining_count: int | None = self.request.rows_limit or None self._operation_metric = metric diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/data/exceptions.py b/packages/google-cloud-bigtable/google/cloud/bigtable/data/exceptions.py index bfc1a9eadddd..475ea1e9742a 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/data/exceptions.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/data/exceptions.py @@ -141,6 +141,8 @@ def __repr__(self): return f"{self.__class__.__name__}({message!r}, {self.exceptions!r})" +# TODO: When working on mutations batcher, rework exception handling to guarantee that +# MutationsExceptionGroup only stores FailedMutationEntryErrors. class MutationsExceptionGroup(_BigtableExceptionGroup): """ Represents one or more exceptions that occur during a bulk mutation operation diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/gapic_version.py b/packages/google-cloud-bigtable/google/cloud/bigtable/gapic_version.py index 80808e348d78..47a60f03e311 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/gapic_version.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.45.0" # {x-release-please-version} +__version__ = "2.46.0" # {x-release-please-version} diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/helpers.py b/packages/google-cloud-bigtable/google/cloud/bigtable/helpers.py index 6bc423f50439..71af2f539f2c 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/helpers.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/helpers.py @@ -28,3 +28,35 @@ def batched(iterable: Iterable[T], n) -> Generator[Tuple[T, ...], None, None]: while batch: yield batch batch = tuple(islice(it, n)) + + +class _MappableAttributesMixin: + """ + Mixin for classes that need some of their attribute names remapped. + + This is for taking some of the classes from the data client row filters + and row range classes that are 1:1 with their legacy client counterparts but with + some of their attributes renamed. To use in a class, override the base class with this mixin + class and define a map _attribute_map from legacy client attributes to data client + attributes. + + Attributes are remapped and redefined in __init__ as well as getattr/setattr. + """ + + def __init__(self, *args, **kwargs): + new_kwargs = {self._attribute_map.get(k, k): v for (k, v) in kwargs.items()} + super(_MappableAttributesMixin, self).__init__(*args, **new_kwargs) + + def __getattr__(self, name): + if name == "_attribute_map": + raise AttributeError + if name not in self._attribute_map: + raise AttributeError + return getattr(self, self._attribute_map[name]) + + def __setattr__(self, name, value): + if name == "_attribute_map": + super(_MappableAttributesMixin, self).__setattr__(name, value) + return + attribute = self._attribute_map.get(name, name) + super(_MappableAttributesMixin, self).__setattr__(attribute, value) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/row.py b/packages/google-cloud-bigtable/google/cloud/bigtable/row.py index 46c58ee182c9..c0131a80e345 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/row.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/row.py @@ -1009,6 +1009,16 @@ def __init__(self, row_key): self._row_key = row_key self._cells = {} + @classmethod + def _from_data_client_row(cls, row): + partial_row_data = cls(row.row_key) + for column_family in row._index: + columns = {} + for column, items in row._index[column_family].items(): + columns[column] = [Cell._from_data_client_cell(item) for item in items] + partial_row_data._cells[column_family] = columns + return partial_row_data + def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented @@ -1212,6 +1222,14 @@ def from_pb(cls, cell_pb): else: return cls(cell_pb.value, cell_pb.timestamp_micros) + @classmethod + def _from_data_client_cell(cls, cell): + return cls( + cell.value, + cell.timestamp_micros, + cell.labels, + ) + @property def timestamp(self): return _datetime_from_microseconds(self.timestamp_micros) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/row_data.py b/packages/google-cloud-bigtable/google/cloud/bigtable/row_data.py index f00b9d568bc4..c55fc2ac72f5 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/row_data.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/row_data.py @@ -14,17 +14,16 @@ """Container for Google Cloud Bigtable Cells and Streaming Row Contents.""" -import copy -import warnings +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Generator -import grpc # type: ignore from google.api_core import exceptions, retry -from google.cloud._helpers import _to_bytes # type: ignore from google.cloud.bigtable.row import Cell, InvalidChunk, PartialRowData -from google.cloud.bigtable.row_merger import _RowMerger, _State -from google.cloud.bigtable_v2.types import bigtable as data_messages_v2_pb2 -from google.cloud.bigtable_v2.types import data as data_v2_pb2 + +if TYPE_CHECKING: + from google.cloud.bigtable.data.row import Row # Some classes need to be re-exported here to keep backwards # compatibility. Those classes were moved to row_merger, but we dont want to @@ -57,36 +56,7 @@ class InvalidRetryRequest(RuntimeError): """Exception raised when retry request is invalid.""" -RETRYABLE_INTERNAL_ERROR_MESSAGES = ( - "rst_stream", - "rst stream", - "received unexpected eos on data frame from server", -) -"""Internal error messages that can be retried during read row and mutation.""" - - -def _retriable_internal_server_error(exc): - """ - Return True if the internal server error is retriable. - """ - return isinstance(exc, exceptions.InternalServerError) and any( - retryable_message in exc.message.lower() - for retryable_message in RETRYABLE_INTERNAL_ERROR_MESSAGES - ) - - -def _retry_read_rows_exception(exc): - """Return True if the exception is retriable for read row requests.""" - if isinstance(exc, grpc.RpcError): - exc = exceptions.from_grpc_error(exc) - - return _retriable_internal_server_error(exc) or isinstance( - exc, (exceptions.ServiceUnavailable, exceptions.DeadlineExceeded) - ) - - DEFAULT_RETRY_READ_ROWS = retry.Retry( - predicate=_retry_read_rows_exception, initial=1.0, maximum=15.0, multiplier=2.0, @@ -102,97 +72,119 @@ def _retry_read_rows_exception(exc): class PartialRowsData(object): """Convenience wrapper for consuming a ``ReadRows`` streaming response. + This class will be returned by the ``read_rows`` method, and should not + be constructed manually. + :type read_method: :class:`client._table_data_client.read_rows` :param read_method: ``ReadRows`` method. - :type request: :class:`data_messages_v2_pb2.ReadRowsRequest` - :param request: The ``ReadRowsRequest`` message used to create a - ReadRowsResponse iterator. If the iterator fails, a new - iterator is created, allowing the scan to continue from - the point just beyond the last successfully read row, - identified by self.last_scanned_row_key. The retry happens - inside of the Retry class, using a predicate for the - expected exceptions during iteration. - - :type retry: :class:`~google.api_core.retry.Retry` - :param retry: (Optional) Retry delay and deadline arguments. To override, - the default value :attr:`DEFAULT_RETRY_READ_ROWS` can be - used and modified with the - :meth:`~google.api_core.retry.Retry.with_delay` method - or the - :meth:`~google.api_core.retry.Retry.with_deadline` method. + :type generator: :class:`Iterable[Row]` + :param generator: The `Row` iterator from :meth:`Table.read_rows`. """ - NEW_ROW = "New row" # No cells yet complete for row - ROW_IN_PROGRESS = "Row in progress" # Some cells complete for row - CELL_IN_PROGRESS = "Cell in progress" # Incomplete cell for row - - STATE_NEW_ROW = 1 - STATE_ROW_IN_PROGRESS = 2 - STATE_CELL_IN_PROGRESS = 3 - - read_states = { - STATE_NEW_ROW: NEW_ROW, - STATE_ROW_IN_PROGRESS: ROW_IN_PROGRESS, - STATE_CELL_IN_PROGRESS: CELL_IN_PROGRESS, - } - - def __init__(self, read_method, request, retry=DEFAULT_RETRY_READ_ROWS): - # Counter for rows returned to the user - self._counter = 0 - self._row_merger = _RowMerger() - - # May be cached from previous response - self.last_scanned_row_key = None - self.read_method = read_method - self.request = request - self.retry = retry - - # The `timeout` parameter must be somewhat greater than the value - # contained in `self.retry`, in order to avoid race-like condition and - # allow registering the first deadline error before invoking the retry. - # Otherwise there is a risk of entering an infinite loop that resets - # the timeout counter just before it being triggered. The increment - # by 1 second here is customary but should not be much less than that. - self.response_iterator = read_method( - request, timeout=self.retry._deadline + 1, retry=self.retry + def __init__( + self, + *args: Any, + generator: Generator[Row, Any, Any] | None = None, + **kwargs: Any, + ) -> None: + self._generator: Generator[Row, Any, Any] + if generator is not None and not args and not kwargs: + self._generator = generator + else: + import warnings + + warnings.warn( + "Direct instantiation of `PartialRowsData` is deprecated " + "and will be removed in a future release. `PartialRowsData` should only be obtained " + "by calling `Table.read_rows()`. An empty stream has been initialized.", + DeprecationWarning, + stacklevel=2, + ) + self._generator = (x for x in ()) + + self.rows: dict[bytes, PartialRowData] = {} + + @classmethod + def _from_generator(cls, generator: Generator[Row, Any, Any]) -> PartialRowsData: + """Internal constructor for Table.read_rows.""" + return cls(generator=generator) + + @property + def state(self): + import warnings + + warnings.warn( + "The `state` attribute on `PartialRowsData` is deprecated " + "and will return None.", + DeprecationWarning, + stacklevel=2, ) + return None - self.rows = {} + @property + def last_scanned_row_key(self): + import warnings - # Flag to stop iteration, for any reason not related to self.retry() - self._cancelled = False + warnings.warn( + "The `last_scanned_row_key` attribute on `PartialRowsData` is deprecated " + "and will return None.", + DeprecationWarning, + stacklevel=2, + ) + return None @property - def state(self): # pragma: NO COVER - """ - DEPRECATED: this property is deprecated and will be removed in the - future. - """ + def read_method(self): + import warnings + warnings.warn( - "`PartialRowsData#state()` is deprecated and will be removed in the future", + "The `read_method` attribute on `PartialRowsData` is deprecated " + "and will return None.", DeprecationWarning, stacklevel=2, ) + return None - # Best effort: try to map internal RowMerger states to old strings for - # backwards compatibility - internal_state = self._row_merger.state - if internal_state == _State.ROW_START: - return self.NEW_ROW - # note: _State.CELL_START, _State.CELL_COMPLETE are transient states - # and will not be visible in between chunks - elif internal_state == _State.CELL_IN_PROGRESS: - return self.CELL_IN_PROGRESS - elif internal_state == _State.ROW_COMPLETE: - return self.NEW_ROW - else: - raise RuntimeError("unexpected internal state: " + self._) + @property + def request(self): + import warnings + + warnings.warn( + "The `request` attribute on `PartialRowsData` is deprecated " + "and will return None.", + DeprecationWarning, + stacklevel=2, + ) + return None + + @property + def retry(self): + import warnings + + warnings.warn( + "The `retry` attribute on `PartialRowsData` is deprecated " + "and will return None.", + DeprecationWarning, + stacklevel=2, + ) + return None + + @property + def response_iterator(self): + import warnings + + warnings.warn( + "The `response_iterator` attribute on `PartialRowsData` is deprecated " + "and will return None.", + DeprecationWarning, + stacklevel=2, + ) + return None def cancel(self): """Cancels the iterator, closing the stream.""" - self._cancelled = True - self.response_iterator.cancel() + self._generator.close() def consume_all(self, max_loops=None): """Consume the streamed responses until there are no more. @@ -202,176 +194,27 @@ def consume_all(self, max_loops=None): class as a generator instead. :type max_loops: int - :param max_loops: (Optional) Maximum number of times to try to consume - an additional ``ReadRowsResponse``. You can use this - to avoid long wait times. + :param max_loops: (Deprecated). Maximum number of times to try to consume + an additional ``ReadRowsResponse``. This parameter is + deprecated and is only kept for backwards compatibility. """ for row in self: self.rows[row.row_key] = row - def _create_retry_request(self): - """Helper for :meth:`__iter__`.""" - req_manager = _ReadRowsRequestManager( - self.request, self.last_scanned_row_key, self._counter - ) - return req_manager.build_updated_request() - - def _on_error(self, exc): - """Helper for :meth:`__iter__`.""" - # restart the read scan from AFTER the last successfully read row - retry_request = self.request - if self.last_scanned_row_key: - retry_request = self._create_retry_request() - - self._row_merger = _RowMerger(self._row_merger.last_seen_row_key) - self.response_iterator = self.read_method(retry_request, retry=self.retry) - - def _read_next(self): - """Helper for :meth:`__iter__`.""" - return next(self.response_iterator) - - def _read_next_response(self): - """Helper for :meth:`__iter__`.""" - resp_protoplus = self.retry(self._read_next, on_error=self._on_error)() - # unwrap the underlying protobuf, there is a significant amount of - # overhead that protoplus imposes for very little gain. The protos - # are not user visible, so we just use the raw protos for merging. - return data_messages_v2_pb2.ReadRowsResponse.pb(resp_protoplus) - def __iter__(self): - """Consume the ``ReadRowsResponse`` s from the stream. - Read the rows and yield each to the reader - - Parse the response and its chunks into a new/existing row in - :attr:`_rows`. Rows are returned in order by row key. + """Consume the ``Row`` s from the stream. + Convert them to ``PartialRowData`` and yield each to the reader. """ - while not self._cancelled: - try: - response = self._read_next_response() - except StopIteration: - self._row_merger.finalize() - break - except InvalidRetryRequest: - self._cancelled = True - break - - for row in self._row_merger.process_chunks(response): - self.last_scanned_row_key = self._row_merger.last_seen_row_key - self._counter += 1 - - yield row - - if self._cancelled: - break - # The last response might not have generated any rows, but it - # could've updated last_scanned_row_key - self.last_scanned_row_key = self._row_merger.last_seen_row_key - - -class _ReadRowsRequestManager(object): - """Update the ReadRowsRequest message in case of failures by - filtering the already read keys. - - :type message: class:`data_messages_v2_pb2.ReadRowsRequest` - :param message: Original ReadRowsRequest containing all of the parameters - of API call - - :type last_scanned_key: bytes - :param last_scanned_key: last successfully scanned key - - :type rows_read_so_far: int - :param rows_read_so_far: total no of rows successfully read so far. - this will be used for updating rows_limit - - """ - - def __init__(self, message, last_scanned_key, rows_read_so_far): - self.message = message - self.last_scanned_key = last_scanned_key - self.rows_read_so_far = rows_read_so_far - - def build_updated_request(self): - """Updates the given message request as per last scanned key""" - - resume_request = data_messages_v2_pb2.ReadRowsRequest() - data_messages_v2_pb2.ReadRowsRequest.copy_from(resume_request, self.message) - - if self.message.rows_limit != 0: - row_limit_remaining = self.message.rows_limit - self.rows_read_so_far - if row_limit_remaining > 0: - resume_request.rows_limit = row_limit_remaining - else: - raise InvalidRetryRequest - - # if neither RowSet.row_keys nor RowSet.row_ranges currently exist, - # add row_range that starts with last_scanned_key as start_key_open - # to request only rows that have not been returned yet - if "rows" not in self.message: - row_range = data_v2_pb2.RowRange(start_key_open=self.last_scanned_key) - resume_request.rows = data_v2_pb2.RowSet(row_ranges=[row_range]) - else: - row_keys = self._filter_rows_keys() - row_ranges = self._filter_row_ranges() - - if len(row_keys) == 0 and len(row_ranges) == 0: - # Avoid sending empty row_keys and row_ranges - # if that was not the intention - raise InvalidRetryRequest - - resume_request.rows = data_v2_pb2.RowSet( - row_keys=row_keys, row_ranges=row_ranges - ) - return resume_request - - def _filter_rows_keys(self): - """Helper for :meth:`build_updated_request`""" - return [ - row_key - for row_key in self.message.rows.row_keys - if row_key > self.last_scanned_key - ] - - def _filter_row_ranges(self): - """Helper for :meth:`build_updated_request`""" - new_row_ranges = [] - - for row_range in self.message.rows.row_ranges: - # if current end_key (open or closed) is set, return its value, - # if not, set to empty string (''). - # NOTE: Empty string in end_key means "end of table" - end_key = self._end_key_set(row_range) - # if end_key is already read, skip to the next row_range - if end_key and self._key_already_read(end_key): - continue - - # if current start_key (open or closed) is set, return its value, - # if not, then set to empty string ('') - # NOTE: Empty string in start_key means "beginning of table" - start_key = self._start_key_set(row_range) - - # if start_key was already read or doesn't exist, - # create a row_range with last_scanned_key as start_key_open - # to be passed to retry request - retry_row_range = row_range - if self._key_already_read(start_key): - retry_row_range = copy.deepcopy(row_range) - retry_row_range.start_key_closed = _to_bytes("") - retry_row_range.start_key_open = self.last_scanned_key - - new_row_ranges.append(retry_row_range) - - return new_row_ranges - - def _key_already_read(self, key): - """Helper for :meth:`_filter_row_ranges`""" - return key <= self.last_scanned_key - - @staticmethod - def _start_key_set(row_range): - """Helper for :meth:`_filter_row_ranges`""" - return row_range.start_key_open or row_range.start_key_closed - - @staticmethod - def _end_key_set(row_range): - """Helper for :meth:`_filter_row_ranges`""" - return row_range.end_key_open or row_range.end_key_closed + try: + for row in self._generator: + yield PartialRowData._from_data_client_row(row) + + # Any exception from the generator should cancel the iterator. A + # timeout, defined by catching a DeadlineExceeded, should be reraised + # as a RetryError instead. + except exceptions.DeadlineExceeded as e: + self.cancel() + raise exceptions.RetryError(e.message, e.__cause__) + except Exception as e: + self.cancel() + raise e diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/row_filters.py b/packages/google-cloud-bigtable/google/cloud/bigtable/row_filters.py index 449543bc132c..433ac7c04ef5 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/row_filters.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/row_filters.py @@ -50,6 +50,7 @@ from google.cloud.bigtable.data.row_filters import ( TimestampRangeFilter as BaseTimestampRangeFilter, ) +from google.cloud.bigtable.helpers import _MappableAttributesMixin _PACK_I64 = struct.Struct(">q").pack @@ -70,35 +71,6 @@ def _deprecated_to_pb(self): # Provide to_pb alias with DeprecationWarning for backwards compatibility with legacy client code RowFilter.to_pb = _deprecated_to_pb # type: ignore[attr-defined] TimestampRange.to_pb = _deprecated_to_pb # type: ignore[attr-defined] - - -class _MappableAttributesMixin: - """ - Mixin for classes that need some of their attribute names remapped. - - This is for taking some of the classes from the data client row filters - that are 1:1 with their legacy client counterparts but with some of their - attributes renamed. To use in a class, override the base class with this mixin - class and define a map _attribute_map from legacy client attributes to data client - attributes. - - Attributes are remapped and redefined in __init__ as well as getattr/setattr. - """ - - def __init__(self, *args, **kwargs): - new_kwargs = {self._attribute_map.get(k, k): v for (k, v) in kwargs.items()} - super(_MappableAttributesMixin, self).__init__(*args, **new_kwargs) - - def __getattr__(self, name): - if name not in self._attribute_map: - raise AttributeError - return getattr(self, self._attribute_map[name]) - - def __setattr__(self, name, value): - attribute = self._attribute_map.get(name, name) - super(_MappableAttributesMixin, self).__setattr__(attribute, value) - - # The classes defined below are to provide constructors and members # that have an interface that does not match the one used by the data # client, for backwards compatibility purposes. diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/row_merger.py b/packages/google-cloud-bigtable/google/cloud/bigtable/row_merger.py deleted file mode 100644 index 6fe9cdca505a..000000000000 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/row_merger.py +++ /dev/null @@ -1,251 +0,0 @@ -from collections import OrderedDict -from enum import Enum - -from google.cloud.bigtable.row import Cell, InvalidChunk, PartialRowData - -_MISSING_COLUMN_FAMILY = "Column family {} is not among the cells stored in this row." -_MISSING_COLUMN = ( - "Column {} is not among the cells stored in this row in the column family {}." -) -_MISSING_INDEX = ( - "Index {!r} is not valid for the cells stored in this row for column {} " - "in the column family {}. There are {} such cells." -) - - -class _State(Enum): - ROW_START = "ROW_START" - CELL_START = "CELL_START" - CELL_IN_PROGRESS = "CELL_IN_PROGRESS" - CELL_COMPLETE = "CELL_COMPLETE" - ROW_COMPLETE = "ROW_COMPLETE" - - -class _PartialRow(object): - __slots__ = [ - "row_key", - "cells", - "last_family", - "last_family_cells", - "last_qualifier", - "last_qualifier_cells", - "cell", - ] - - def __init__(self, row_key): - self.row_key = row_key - self.cells = OrderedDict() - - self.last_family = None - self.last_family_cells = OrderedDict() - self.last_qualifier = None - self.last_qualifier_cells = [] - - self.cell = None - - -class _PartialCell(object): - __slots__ = ["family", "qualifier", "timestamp", "labels", "value", "value_index"] - - def __init__(self): - self.family = None - self.qualifier = None - self.timestamp = None - self.labels = None - self.value = None - self.value_index = 0 - - -class _RowMerger(object): - """ - State machine to merge chunks from a response stream into logical rows. - - The implementation is a fairly linear state machine that is implemented as - a method for every state in the _State enum. In general the states flow - from top to bottom with some repetition. Each state handler will do some - sanity checks, update in progress data and set the next state. - - There can be multiple state transitions for each chunk, i.e. a single chunk - row will flow from ROW_START -> CELL_START -> CELL_COMPLETE -> ROW_COMPLETE - in a single iteration. - """ - - __slots__ = ["state", "last_seen_row_key", "row"] - - def __init__(self, last_seen_row=b""): - self.last_seen_row_key = last_seen_row - self.state = _State.ROW_START - self.row = None - - def process_chunks(self, response): - """ - Process the chunks in the given response and yield logical rows. - This class will maintain state across multiple response protos. - """ - if response.last_scanned_row_key: - if self.last_seen_row_key >= response.last_scanned_row_key: - raise InvalidChunk("Last scanned row key is out of order") - self.last_seen_row_key = response.last_scanned_row_key - - for chunk in response.chunks: - if chunk.reset_row: - self._handle_reset(chunk) - continue - - if self.state == _State.ROW_START: - self._handle_row_start(chunk) - - if self.state == _State.CELL_START: - self._handle_cell_start(chunk) - - if self.state == _State.CELL_IN_PROGRESS: - self._handle_cell_in_progress(chunk) - - if self.state == _State.CELL_COMPLETE: - self._handle_cell_complete(chunk) - - if self.state == _State.ROW_COMPLETE: - yield self._handle_row_complete(chunk) - elif chunk.commit_row: - raise InvalidChunk( - f"Chunk tried to commit row in wrong state (${self.state})" - ) - - def _handle_reset(self, chunk): - if self.state == _State.ROW_START: - raise InvalidChunk("Bare reset") - if chunk.row_key: - raise InvalidChunk("Reset chunk has a row key") - if chunk.HasField("family_name"): - raise InvalidChunk("Reset chunk has family_name") - if chunk.HasField("qualifier"): - raise InvalidChunk("Reset chunk has qualifier") - if chunk.timestamp_micros: - raise InvalidChunk("Reset chunk has a timestamp") - if chunk.labels: - raise InvalidChunk("Reset chunk has labels") - if chunk.value: - raise InvalidChunk("Reset chunk has a value") - - self.state = _State.ROW_START - self.row = None - - def _handle_row_start(self, chunk): - if not chunk.row_key: - raise InvalidChunk("New row is missing a row key") - if self.last_seen_row_key and self.last_seen_row_key >= chunk.row_key: - raise InvalidChunk("Out of order row keys") - - self.row = _PartialRow(chunk.row_key) - self.state = _State.CELL_START - - def _handle_cell_start(self, chunk): - # Ensure that all chunks after the first one either are missing a row - # key or the row is the same - if self.row.cells and chunk.row_key and chunk.row_key != self.row.row_key: - raise InvalidChunk("row key changed mid row") - - if not self.row.cell: - self.row.cell = _PartialCell() - - # Cells can inherit family/qualifier from previous cells - # However if the family changes, then qualifier must be specified as well - if chunk.HasField("family_name"): - self.row.cell.family = chunk.family_name.value - self.row.cell.qualifier = None - if not self.row.cell.family: - raise InvalidChunk("missing family for a new cell") - - if chunk.HasField("qualifier"): - self.row.cell.qualifier = chunk.qualifier.value - if self.row.cell.qualifier is None: - raise InvalidChunk("missing qualifier for a new cell") - - self.row.cell.timestamp = chunk.timestamp_micros - self.row.cell.labels = chunk.labels - - if chunk.value_size > 0: - # explicitly avoid pre-allocation as it seems that bytearray - # concatenation performs better than slice copies. - self.row.cell.value = bytearray() - self.state = _State.CELL_IN_PROGRESS - else: - self.row.cell.value = chunk.value - self.state = _State.CELL_COMPLETE - - def _handle_cell_in_progress(self, chunk): - # if this isn't the first cell chunk, make sure that everything except - # the value stayed constant. - if self.row.cell.value_index > 0: - if chunk.row_key: - raise InvalidChunk("found row key mid cell") - if chunk.HasField("family_name"): - raise InvalidChunk("In progress cell had a family name") - if chunk.HasField("qualifier"): - raise InvalidChunk("In progress cell had a qualifier") - if chunk.timestamp_micros: - raise InvalidChunk("In progress cell had a timestamp") - if chunk.labels: - raise InvalidChunk("In progress cell had labels") - - self.row.cell.value += chunk.value - self.row.cell.value_index += len(chunk.value) - - if chunk.value_size > 0: - self.state = _State.CELL_IN_PROGRESS - else: - self.row.cell.value = bytes(self.row.cell.value) - self.state = _State.CELL_COMPLETE - - def _handle_cell_complete(self, chunk): - # since we are guaranteed that all family & qualifier cells are - # contiguous, we can optimize away the dict lookup by caching the last - # family/qualifier and simply comparing and appending - family_changed = False - if self.row.last_family != self.row.cell.family: - family_changed = True - self.row.last_family = self.row.cell.family - self.row.cells[self.row.cell.family] = self.row.last_family_cells = ( - OrderedDict() - ) - - if family_changed or self.row.last_qualifier != self.row.cell.qualifier: - self.row.last_qualifier = self.row.cell.qualifier - self.row.last_family_cells[self.row.cell.qualifier] = ( - self.row.last_qualifier_cells - ) = [] - - self.row.last_qualifier_cells.append( - Cell( - self.row.cell.value, - self.row.cell.timestamp, - self.row.cell.labels, - ) - ) - - self.row.cell.timestamp = 0 - self.row.cell.value = None - self.row.cell.value_index = 0 - - if not chunk.commit_row: - self.state = _State.CELL_START - else: - self.state = _State.ROW_COMPLETE - - def _handle_row_complete(self, chunk): - new_row = PartialRowData(self.row.row_key) - new_row._cells = self.row.cells - - self.last_seen_row_key = new_row.row_key - self.row = None - self.state = _State.ROW_START - - return new_row - - def finalize(self): - """ - Must be called at the end of the stream to ensure there are no unmerged - rows. - """ - if self.row or self.state != _State.ROW_START: - raise ValueError("The row remains partial / is not committed.") diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/row_set.py b/packages/google-cloud-bigtable/google/cloud/bigtable/row_set.py index 99dae972a6be..4e4bacfa7cda 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/row_set.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/row_set.py @@ -14,7 +14,13 @@ """User-friendly container for Google Cloud Bigtable RowSet""" -from google.cloud._helpers import _to_bytes # type: ignore +from google.cloud.bigtable.data.read_rows_query import ( + ReadRowsQuery, +) +from google.cloud.bigtable.data.read_rows_query import ( + RowRange as BaseRowRange, +) +from google.cloud.bigtable.helpers import _MappableAttributesMixin class RowSet(object): @@ -25,30 +31,25 @@ class RowSet(object): """ def __init__(self): - self.row_keys = [] - self.row_ranges = [] + self._read_rows_query = ReadRowsQuery() def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented - if len(other.row_keys) != len(self.row_keys): - return False - - if len(other.row_ranges) != len(self.row_ranges): - return False - - if not set(other.row_keys) == set(self.row_keys): - return False - - if not set(other.row_ranges) == set(self.row_ranges): - return False - - return True + return self._read_rows_query == other._read_rows_query def __ne__(self, other): return not self == other + @property + def row_keys(self): + return self._read_rows_query.row_keys + + @property + def row_ranges(self): + return self._read_rows_query.row_ranges + def add_row_key(self, row_key): """Add row key to row_keys list. @@ -62,7 +63,7 @@ def add_row_key(self, row_key): :type row_key: bytes :param row_key: The key of a row to read """ - self.row_keys.append(row_key) + self._read_rows_query.add_key(row_key) def add_row_range(self, row_range): """Add row_range to row_ranges list. @@ -77,7 +78,7 @@ def add_row_range(self, row_range): :type row_range: class:`RowRange` :param row_range: The row range object having start and end key """ - self.row_ranges.append(row_range) + self._read_rows_query.add_range(row_range) def add_row_range_from_keys( self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False @@ -109,7 +110,7 @@ def add_row_range_from_keys( considered inclusive. The default is False (exclusive). """ row_range = RowRange(start_key, end_key, start_inclusive, end_inclusive) - self.row_ranges.append(row_range) + self._read_rows_query.add_range(row_range) def add_row_range_with_prefix(self, row_key_prefix): """Add row range to row_ranges list that start with the row_key_prefix from the row keys @@ -129,28 +130,15 @@ def add_row_range_with_prefix(self, row_key_prefix): row_key_prefix.encode("utf-8"), end_key.encode("utf-8") ) - def _update_message_request(self, message): - """Add row keys and row range to given request message - :type message: class:`data_messages_v2_pb2.ReadRowsRequest` - :param message: The ``ReadRowsRequest`` protobuf - """ - for each in self.row_keys: - message.rows.row_keys._pb.append(_to_bytes(each)) - - for each in self.row_ranges: - r_kwrags = each.get_range_kwargs() - message.rows.row_ranges.append(r_kwrags) - - -class RowRange(object): +class RowRange(_MappableAttributesMixin, BaseRowRange): """Convenience wrapper of google.bigtable.v2.RowRange - :type start_key: bytes + :type start_key: str | bytes :param start_key: (Optional) Start key of the row range. If left empty, will be interpreted as the empty string. - :type end_key: bytes + :type end_key: str | bytes :param end_key: (Optional) End key of the row range. If left empty, will be interpreted as the empty string and range will be unbounded on the high end. @@ -164,49 +152,31 @@ class RowRange(object): considered inclusive. The default is False (exclusive). """ - def __init__( - self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False - ): - self.start_key = start_key - self.start_inclusive = start_inclusive - self.end_key = end_key - self.end_inclusive = end_inclusive + _attribute_map = { + "start_inclusive": "start_is_inclusive", + "end_inclusive": "end_is_inclusive", + } def _key(self): - """A tuple key that uniquely describes this field. - - Used to compute this instance's hashcode and evaluate equality. - - Returns: - Tuple[str]: The contents of this :class:`.RowRange`. - """ - return (self.start_key, self.start_inclusive, self.end_key, self.end_inclusive) + return ( + self.start_key, + self.end_key, + self.start_is_inclusive, + self.end_is_inclusive, + ) def __hash__(self): return hash(self._key()) - def __eq__(self, other): - if not isinstance(other, self.__class__): - return NotImplemented - return self._key() == other._key() - - def __ne__(self, other): - return not self == other - def get_range_kwargs(self): """Convert row range object to dict which can be passed to google.bigtable.v2.RowRange add method. """ range_kwargs = {} if self.start_key is not None: - start_key_key = "start_key_open" - if self.start_inclusive: - start_key_key = "start_key_closed" - range_kwargs[start_key_key] = _to_bytes(self.start_key) - + key = "start_key_closed" if self.start_is_inclusive else "start_key_open" + range_kwargs[key] = self.start_key if self.end_key is not None: - end_key_key = "end_key_open" - if self.end_inclusive: - end_key_key = "end_key_closed" - range_kwargs[end_key_key] = _to_bytes(self.end_key) + key = "end_key_closed" if self.end_is_inclusive else "end_key_open" + range_kwargs[key] = self.end_key return range_kwargs diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable/table.py b/packages/google-cloud-bigtable/google/cloud/bigtable/table.py index 74f37e6ae1e8..31704226c1db 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable/table.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable/table.py @@ -44,20 +44,25 @@ RetryExceptionGroup, ) from google.cloud.bigtable.data.mutations import RowMutationEntry +from google.cloud.bigtable.data.read_rows_query import ReadRowsQuery from google.cloud.bigtable.encryption_info import EncryptionInfo from google.cloud.bigtable.policy import Policy -from google.cloud.bigtable.row import AppendRow, ConditionalRow, DirectRow +from google.cloud.bigtable.row import ( + AppendRow, + ConditionalRow, + DirectRow, + PartialRowData, +) from google.cloud.bigtable.row_data import ( DEFAULT_RETRY_READ_ROWS, PartialRowsData, ) -from google.cloud.bigtable.row_set import RowRange, RowSet +from google.cloud.bigtable.row_set import RowRange from google.cloud.bigtable_admin_v2 import BaseBigtableTableAdminClient from google.cloud.bigtable_admin_v2.types import ( bigtable_table_admin as table_admin_messages_v2_pb2, ) from google.cloud.bigtable_admin_v2.types import table as admin_messages_v2_pb2 -from google.cloud.bigtable_v2.types import bigtable as data_messages_v2_pb2 # Maximum number of mutations in bulk (MutateRowsRequest message): # (https://cloud.google.com/bigtable/docs/reference/data/rpc/ @@ -573,18 +578,23 @@ def read_row(self, row_key, filter_=None, retry=DEFAULT_RETRY_READ_ROWS): :rtype: :class:`.PartialRowData`, :data:`NoneType ` :returns: The contents of the row if any chunks were returned in the response, otherwise :data:`None`. - :raises: :class:`ValueError ` if a commit row - chunk is never encountered. """ - row_set = RowSet() - row_set.add_row_key(row_key) - result_iter = iter( - self.read_rows(filter_=filter_, row_set=row_set, retry=retry) + attempt_timeout = ( + getattr(retry, "deadline", None) + or getattr(retry, "_deadline", None) + or TABLE_DEFAULT.READ_ROWS + ) + row = self._table_impl.read_row( + row_key, + row_filter=filter_, + operation_timeout=TABLE_DEFAULT.READ_ROWS, + attempt_timeout=attempt_timeout, + retryable_errors=TABLE_DEFAULT.READ_ROWS, ) - row = next(result_iter, None) - if next(result_iter, None) is not None: - raise ValueError("More than one row was returned.") - return row + if row is None: + return None + + return PartialRowData._from_data_client_row(row) def read_rows( self, @@ -645,18 +655,26 @@ def read_rows( :returns: A :class:`.PartialRowsData` a generator for consuming the streamed results. """ - request_pb = _create_row_request( - self.name, + attempt_timeout = ( + getattr(retry, "deadline", None) + or getattr(retry, "_deadline", None) + or TABLE_DEFAULT.READ_ROWS + ) + query = _create_row_request( start_key=start_key, end_key=end_key, filter_=filter_, limit=limit, end_inclusive=end_inclusive, - app_profile_id=self._app_profile_id, row_set=row_set, ) - data_client = self._instance._client.table_data_client - return PartialRowsData(data_client.read_rows, request_pb, retry) + generator = self._table_impl.read_rows_stream( + query, + operation_timeout=TABLE_DEFAULT.READ_ROWS, + attempt_timeout=attempt_timeout, + retryable_errors=TABLE_DEFAULT.READ_ROWS, + ) + return PartialRowsData._from_generator(generator) def yield_rows(self, **kwargs): """Read rows from this table. @@ -1235,13 +1253,11 @@ def __ne__(self, other): def _create_row_request( - table_name, start_key=None, end_key=None, filter_=None, limit=None, end_inclusive=False, - app_profile_id=None, row_set=None, ): """Creates a request to read rows in a table. @@ -1272,36 +1288,32 @@ def _create_row_request( :param end_inclusive: (Optional) Whether the ``end_key`` should be considered inclusive. The default is False (exclusive). - :type: app_profile_id: str - :param app_profile_id: (Optional) The unique name of the AppProfile. - :type row_set: :class:`.RowSet` :param row_set: (Optional) The row set containing multiple row keys and row_ranges. - :rtype: :class:`data_messages_v2_pb2.ReadRowsRequest` - :returns: The ``ReadRowsRequest`` protobuf corresponding to the inputs. + :rtype: :class:`ReadRowsQuery` + :returns: The `ReadRowsQuery` query object corresponding to the inputs. :raises: :class:`ValueError ` if both - ``row_set`` and one of ``start_key`` or ``end_key`` are set + ``row_set`` and one of ``start_key`` or ``end_key`` are set, or if + ``end_key`` is not greater than ``start_key`` """ - request_kwargs = {"table_name": table_name} if (start_key is not None or end_key is not None) and row_set is not None: raise ValueError("Row range and row set cannot be set simultaneously") - if filter_ is not None: - request_kwargs["filter"] = filter_._to_pb() - if limit is not None: - request_kwargs["rows_limit"] = limit - if app_profile_id is not None: - request_kwargs["app_profile_id"] = app_profile_id - - message = data_messages_v2_pb2.ReadRowsRequest(**request_kwargs) + query = ReadRowsQuery( + limit=limit, + row_filter=filter_, + ) if start_key is not None or end_key is not None: - row_set = RowSet() - row_set.add_row_range(RowRange(start_key, end_key, end_inclusive=end_inclusive)) + query.add_range(RowRange(start_key, end_key, end_inclusive=end_inclusive)) if row_set is not None: - row_set._update_message_request(message) + for row_key in row_set.row_keys: + query.add_key(row_key) + + for row_range in row_set.row_ranges: + query.add_range(row_range) - return message + return query diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin/__init__.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin/__init__.py index adbde8eb4412..61eb1ecc9972 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin/__init__.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin/__init__.py @@ -50,6 +50,7 @@ GetInstanceRequest, GetLogicalViewRequest, GetMaterializedViewRequest, + GetMemoryLayerRequest, ListAppProfilesRequest, ListAppProfilesResponse, ListClustersRequest, @@ -62,6 +63,8 @@ ListLogicalViewsResponse, ListMaterializedViewsRequest, ListMaterializedViewsResponse, + ListMemoryLayersRequest, + ListMemoryLayersResponse, PartialUpdateClusterMetadata, PartialUpdateClusterRequest, PartialUpdateInstanceRequest, @@ -73,6 +76,8 @@ UpdateLogicalViewRequest, UpdateMaterializedViewMetadata, UpdateMaterializedViewRequest, + UpdateMemoryLayerMetadata, + UpdateMemoryLayerRequest, ) from google.cloud.bigtable_admin_v2.types.bigtable_table_admin import ( CheckConsistencyRequest, @@ -139,6 +144,7 @@ Instance, LogicalView, MaterializedView, + MemoryLayer, ) from google.cloud.bigtable_admin_v2.types.table import ( AuthorizedView, @@ -184,6 +190,7 @@ "GetInstanceRequest", "GetLogicalViewRequest", "GetMaterializedViewRequest", + "GetMemoryLayerRequest", "ListAppProfilesRequest", "ListAppProfilesResponse", "ListClustersRequest", @@ -196,6 +203,8 @@ "ListLogicalViewsResponse", "ListMaterializedViewsRequest", "ListMaterializedViewsResponse", + "ListMemoryLayersRequest", + "ListMemoryLayersResponse", "PartialUpdateClusterMetadata", "PartialUpdateClusterRequest", "PartialUpdateInstanceRequest", @@ -207,6 +216,8 @@ "UpdateLogicalViewRequest", "UpdateMaterializedViewMetadata", "UpdateMaterializedViewRequest", + "UpdateMemoryLayerMetadata", + "UpdateMemoryLayerRequest", "CheckConsistencyRequest", "CheckConsistencyResponse", "CopyBackupMetadata", @@ -270,6 +281,7 @@ "Instance", "LogicalView", "MaterializedView", + "MemoryLayer", "AuthorizedView", "AvroSchema", "Backup", diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin/gapic_version.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin/gapic_version.py index 80808e348d78..47a60f03e311 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin/gapic_version.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.45.0" # {x-release-please-version} +__version__ = "2.46.0" # {x-release-please-version} diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/__init__.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/__init__.py index 1554135ceba0..fc40058b6028 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/__init__.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/__init__.py @@ -65,6 +65,7 @@ GetInstanceRequest, GetLogicalViewRequest, GetMaterializedViewRequest, + GetMemoryLayerRequest, ListAppProfilesRequest, ListAppProfilesResponse, ListClustersRequest, @@ -77,6 +78,8 @@ ListLogicalViewsResponse, ListMaterializedViewsRequest, ListMaterializedViewsResponse, + ListMemoryLayersRequest, + ListMemoryLayersResponse, PartialUpdateClusterMetadata, PartialUpdateClusterRequest, PartialUpdateInstanceRequest, @@ -88,6 +91,8 @@ UpdateLogicalViewRequest, UpdateMaterializedViewMetadata, UpdateMaterializedViewRequest, + UpdateMemoryLayerMetadata, + UpdateMemoryLayerRequest, ) from .types.bigtable_table_admin import ( CheckConsistencyRequest, @@ -154,6 +159,7 @@ Instance, LogicalView, MaterializedView, + MemoryLayer, ) from .types.table import ( AuthorizedView, @@ -235,6 +241,7 @@ "GetInstanceRequest", "GetLogicalViewRequest", "GetMaterializedViewRequest", + "GetMemoryLayerRequest", "GetSchemaBundleRequest", "GetSnapshotRequest", "GetTableRequest", @@ -256,6 +263,8 @@ "ListLogicalViewsResponse", "ListMaterializedViewsRequest", "ListMaterializedViewsResponse", + "ListMemoryLayersRequest", + "ListMemoryLayersResponse", "ListSchemaBundlesRequest", "ListSchemaBundlesResponse", "ListSnapshotsRequest", @@ -264,6 +273,7 @@ "ListTablesResponse", "LogicalView", "MaterializedView", + "MemoryLayer", "ModifyColumnFamiliesRequest", "OperationProgress", "OptimizeRestoredTableMetadata", @@ -298,6 +308,8 @@ "UpdateLogicalViewRequest", "UpdateMaterializedViewMetadata", "UpdateMaterializedViewRequest", + "UpdateMemoryLayerMetadata", + "UpdateMemoryLayerRequest", "UpdateSchemaBundleMetadata", "UpdateSchemaBundleRequest", "UpdateTableMetadata", diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_metadata.json b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_metadata.json index 9725d3384819..887587fec0b4 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_metadata.json +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_metadata.json @@ -90,6 +90,11 @@ "get_materialized_view" ] }, + "GetMemoryLayer": { + "methods": [ + "get_memory_layer" + ] + }, "ListAppProfiles": { "methods": [ "list_app_profiles" @@ -120,6 +125,11 @@ "list_materialized_views" ] }, + "ListMemoryLayers": { + "methods": [ + "list_memory_layers" + ] + }, "PartialUpdateCluster": { "methods": [ "partial_update_cluster" @@ -164,6 +174,11 @@ "methods": [ "update_materialized_view" ] + }, + "UpdateMemoryLayer": { + "methods": [ + "update_memory_layer" + ] } } }, @@ -250,6 +265,11 @@ "get_materialized_view" ] }, + "GetMemoryLayer": { + "methods": [ + "get_memory_layer" + ] + }, "ListAppProfiles": { "methods": [ "list_app_profiles" @@ -280,6 +300,11 @@ "list_materialized_views" ] }, + "ListMemoryLayers": { + "methods": [ + "list_memory_layers" + ] + }, "PartialUpdateCluster": { "methods": [ "partial_update_cluster" @@ -324,6 +349,11 @@ "methods": [ "update_materialized_view" ] + }, + "UpdateMemoryLayer": { + "methods": [ + "update_memory_layer" + ] } } }, @@ -410,6 +440,11 @@ "get_materialized_view" ] }, + "GetMemoryLayer": { + "methods": [ + "get_memory_layer" + ] + }, "ListAppProfiles": { "methods": [ "list_app_profiles" @@ -440,6 +475,11 @@ "list_materialized_views" ] }, + "ListMemoryLayers": { + "methods": [ + "list_memory_layers" + ] + }, "PartialUpdateCluster": { "methods": [ "partial_update_cluster" @@ -484,6 +524,11 @@ "methods": [ "update_materialized_view" ] + }, + "UpdateMemoryLayer": { + "methods": [ + "update_memory_layer" + ] } } } diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_version.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_version.py index 80808e348d78..47a60f03e311 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_version.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.45.0" # {x-release-please-version} +__version__ = "2.46.0" # {x-release-please-version} diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py index 932f2e4fec3b..b394196bc813 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/async_client.py @@ -115,6 +115,10 @@ class BigtableInstanceAdminAsyncClient: parse_materialized_view_path = staticmethod( BigtableInstanceAdminClient.parse_materialized_view_path ) + memory_layer_path = staticmethod(BigtableInstanceAdminClient.memory_layer_path) + parse_memory_layer_path = staticmethod( + BigtableInstanceAdminClient.parse_memory_layer_path + ) table_path = staticmethod(BigtableInstanceAdminClient.table_path) parse_table_path = staticmethod(BigtableInstanceAdminClient.parse_table_path) common_billing_account_path = staticmethod( @@ -1852,6 +1856,399 @@ async def sample_delete_cluster(): metadata=metadata, ) + async def update_memory_layer( + self, + request: Optional[ + Union[bigtable_instance_admin.UpdateMemoryLayerRequest, dict] + ] = None, + *, + memory_layer: Optional[instance.MemoryLayer] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the memory layer of a cluster. + + To enable the memory layer, set the memory_config. To disable + the memory layer, unset the memory_config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import bigtable_admin_v2 + + async def sample_update_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminAsyncClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.UpdateMemoryLayerRequest( + ) + + # Make the request + operation = await client.update_memory_layer(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.UpdateMemoryLayerRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.UpdateMemoryLayer. + memory_layer (:class:`google.cloud.bigtable_admin_v2.types.MemoryLayer`): + Required. The memory layer to update. + + The memory layer's ``name`` format is as follows: + ``projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer``. + + This corresponds to the ``memory_layer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.bigtable_admin_v2.types.MemoryLayer` The memory layer of a cluster. A memory layer serves reads from + memory without hitting the backing persistent data + store. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [memory_layer, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.UpdateMemoryLayerRequest): + request = bigtable_instance_admin.UpdateMemoryLayerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if memory_layer is not None: + request.memory_layer = memory_layer + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_memory_layer + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("memory_layer.name", request.memory_layer.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + instance.MemoryLayer, + metadata_type=bigtable_instance_admin.UpdateMemoryLayerMetadata, + ) + + # Done; return the response. + return response + + async def list_memory_layers( + self, + request: Optional[ + Union[bigtable_instance_admin.ListMemoryLayersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMemoryLayersAsyncPager: + r"""Lists information about memory layers. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import bigtable_admin_v2 + + async def sample_list_memory_layers(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminAsyncClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.ListMemoryLayersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memory_layers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.ListMemoryLayersRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.ListMemoryLayers. + parent (:class:`str`): + Required. The unique name of the cluster for which a + list of memory layers is requested. Values are of the + form + ``projects/{project}/instances/{instance}/clusters/{cluster}``. + Use ``{cluster} = '-'`` to list MemoryLayers for all + Clusters in an instance, e.g., + ``projects/myproject/instances/myinstance/clusters/-``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListMemoryLayersAsyncPager: + Response message for + BigtableInstanceAdmin.ListMemoryLayers. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.ListMemoryLayersRequest): + request = bigtable_instance_admin.ListMemoryLayersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_memory_layers + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMemoryLayersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_memory_layer( + self, + request: Optional[ + Union[bigtable_instance_admin.GetMemoryLayerRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.MemoryLayer: + r"""Gets information about the memory layer of a cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import bigtable_admin_v2 + + async def sample_get_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminAsyncClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.GetMemoryLayerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_memory_layer(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.bigtable_admin_v2.types.GetMemoryLayerRequest, dict]]): + The request object. Request message for + BigtableInstanceAdmin.GetMemoryLayer. + name (:class:`str`): + Required. The unique name of the requested cluster's + memory layer. Values are of the form + ``projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.types.MemoryLayer: + The memory layer of a cluster. A + memory layer serves reads from memory + without hitting the backing persistent + data store. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.GetMemoryLayerRequest): + request = bigtable_instance_admin.GetMemoryLayerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_memory_layer + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def create_app_profile( self, request: Optional[ diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py index 3757030197d3..ed8dd56b5e6b 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/client.py @@ -340,6 +340,28 @@ def parse_materialized_view_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def memory_layer_path( + project: str, + instance: str, + cluster: str, + ) -> str: + """Returns a fully-qualified memory_layer string.""" + return "projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer".format( + project=project, + instance=instance, + cluster=cluster, + ) + + @staticmethod + def parse_memory_layer_path(path: str) -> Dict[str, str]: + """Parses a memory_layer path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/instances/(?P.+?)/clusters/(?P.+?)/memoryLayer$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def table_path( project: str, @@ -2240,6 +2262,390 @@ def sample_delete_cluster(): metadata=metadata, ) + def update_memory_layer( + self, + request: Optional[ + Union[bigtable_instance_admin.UpdateMemoryLayerRequest, dict] + ] = None, + *, + memory_layer: Optional[instance.MemoryLayer] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the memory layer of a cluster. + + To enable the memory layer, set the memory_config. To disable + the memory layer, unset the memory_config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import bigtable_admin_v2 + + def sample_update_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.UpdateMemoryLayerRequest( + ) + + # Make the request + operation = client.update_memory_layer(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.UpdateMemoryLayerRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.UpdateMemoryLayer. + memory_layer (google.cloud.bigtable_admin_v2.types.MemoryLayer): + Required. The memory layer to update. + + The memory layer's ``name`` format is as follows: + ``projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer``. + + This corresponds to the ``memory_layer`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.bigtable_admin_v2.types.MemoryLayer` The memory layer of a cluster. A memory layer serves reads from + memory without hitting the backing persistent data + store. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [memory_layer, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.UpdateMemoryLayerRequest): + request = bigtable_instance_admin.UpdateMemoryLayerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if memory_layer is not None: + request.memory_layer = memory_layer + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_memory_layer] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("memory_layer.name", request.memory_layer.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + instance.MemoryLayer, + metadata_type=bigtable_instance_admin.UpdateMemoryLayerMetadata, + ) + + # Done; return the response. + return response + + def list_memory_layers( + self, + request: Optional[ + Union[bigtable_instance_admin.ListMemoryLayersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMemoryLayersPager: + r"""Lists information about memory layers. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import bigtable_admin_v2 + + def sample_list_memory_layers(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.ListMemoryLayersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memory_layers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.ListMemoryLayersRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.ListMemoryLayers. + parent (str): + Required. The unique name of the cluster for which a + list of memory layers is requested. Values are of the + form + ``projects/{project}/instances/{instance}/clusters/{cluster}``. + Use ``{cluster} = '-'`` to list MemoryLayers for all + Clusters in an instance, e.g., + ``projects/myproject/instances/myinstance/clusters/-``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListMemoryLayersPager: + Response message for + BigtableInstanceAdmin.ListMemoryLayers. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.ListMemoryLayersRequest): + request = bigtable_instance_admin.ListMemoryLayersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_memory_layers] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMemoryLayersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_memory_layer( + self, + request: Optional[ + Union[bigtable_instance_admin.GetMemoryLayerRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.MemoryLayer: + r"""Gets information about the memory layer of a cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import bigtable_admin_v2 + + def sample_get_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.GetMemoryLayerRequest( + name="name_value", + ) + + # Make the request + response = client.get_memory_layer(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.bigtable_admin_v2.types.GetMemoryLayerRequest, dict]): + The request object. Request message for + BigtableInstanceAdmin.GetMemoryLayer. + name (str): + Required. The unique name of the requested cluster's + memory layer. Values are of the form + ``projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigtable_admin_v2.types.MemoryLayer: + The memory layer of a cluster. A + memory layer serves reads from memory + without hitting the backing persistent + data store. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, bigtable_instance_admin.GetMemoryLayerRequest): + request = bigtable_instance_admin.GetMemoryLayerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_memory_layer] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def create_app_profile( self, request: Optional[ diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py index 3698d13f7235..26c4c10e1a9d 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/pagers.py @@ -41,6 +41,166 @@ from google.cloud.bigtable_admin_v2.types import bigtable_instance_admin, instance +class ListMemoryLayersPager: + """A pager for iterating through ``list_memory_layers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigtable_admin_v2.types.ListMemoryLayersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``memory_layers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMemoryLayers`` requests and continue to iterate + through the ``memory_layers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigtable_admin_v2.types.ListMemoryLayersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., bigtable_instance_admin.ListMemoryLayersResponse], + request: bigtable_instance_admin.ListMemoryLayersRequest, + response: bigtable_instance_admin.ListMemoryLayersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.bigtable_admin_v2.types.ListMemoryLayersRequest): + The initial request object. + response (google.cloud.bigtable_admin_v2.types.ListMemoryLayersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bigtable_instance_admin.ListMemoryLayersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[bigtable_instance_admin.ListMemoryLayersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[instance.MemoryLayer]: + for page in self.pages: + yield from page.memory_layers + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMemoryLayersAsyncPager: + """A pager for iterating through ``list_memory_layers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.bigtable_admin_v2.types.ListMemoryLayersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``memory_layers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMemoryLayers`` requests and continue to iterate + through the ``memory_layers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.bigtable_admin_v2.types.ListMemoryLayersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[bigtable_instance_admin.ListMemoryLayersResponse] + ], + request: bigtable_instance_admin.ListMemoryLayersRequest, + response: bigtable_instance_admin.ListMemoryLayersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.bigtable_admin_v2.types.ListMemoryLayersRequest): + The initial request object. + response (google.cloud.bigtable_admin_v2.types.ListMemoryLayersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = bigtable_instance_admin.ListMemoryLayersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[bigtable_instance_admin.ListMemoryLayersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[instance.MemoryLayer]: + async def async_generator(): + async for page in self.pages: + for response in page.memory_layers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListAppProfilesPager: """A pager for iterating through ``list_app_profiles`` requests. diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py index 8d81f32f44ca..1532f7cd1c0f 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/base.py @@ -282,6 +282,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.update_memory_layer: gapic_v1.method.wrap_method( + self.update_memory_layer, + default_timeout=None, + client_info=client_info, + ), + self.list_memory_layers: gapic_v1.method.wrap_method( + self.list_memory_layers, + default_timeout=None, + client_info=client_info, + ), + self.get_memory_layer: gapic_v1.method.wrap_method( + self.get_memory_layer, + default_timeout=None, + client_info=client_info, + ), self.create_app_profile: gapic_v1.method.wrap_method( self.create_app_profile, default_timeout=60.0, @@ -566,6 +581,36 @@ def delete_cluster( ]: raise NotImplementedError() + @property + def update_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMemoryLayerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_memory_layers( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMemoryLayersRequest], + Union[ + bigtable_instance_admin.ListMemoryLayersResponse, + Awaitable[bigtable_instance_admin.ListMemoryLayersResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMemoryLayerRequest], + Union[instance.MemoryLayer, Awaitable[instance.MemoryLayer]], + ]: + raise NotImplementedError() + @property def create_app_profile( self, diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py index 5be58c50ea9e..0ac09d8610d7 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc.py @@ -705,6 +705,94 @@ def delete_cluster( ) return self._stubs["delete_cluster"] + @property + def update_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMemoryLayerRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update memory layer method over gRPC. + + Updates the memory layer of a cluster. + + To enable the memory layer, set the memory_config. To disable + the memory layer, unset the memory_config. + + Returns: + Callable[[~.UpdateMemoryLayerRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_memory_layer" not in self._stubs: + self._stubs["update_memory_layer"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateMemoryLayer", + request_serializer=bigtable_instance_admin.UpdateMemoryLayerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_memory_layer"] + + @property + def list_memory_layers( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMemoryLayersRequest], + bigtable_instance_admin.ListMemoryLayersResponse, + ]: + r"""Return a callable for the list memory layers method over gRPC. + + Lists information about memory layers. + + Returns: + Callable[[~.ListMemoryLayersRequest], + ~.ListMemoryLayersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_memory_layers" not in self._stubs: + self._stubs["list_memory_layers"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListMemoryLayers", + request_serializer=bigtable_instance_admin.ListMemoryLayersRequest.serialize, + response_deserializer=bigtable_instance_admin.ListMemoryLayersResponse.deserialize, + ) + return self._stubs["list_memory_layers"] + + @property + def get_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMemoryLayerRequest], instance.MemoryLayer + ]: + r"""Return a callable for the get memory layer method over gRPC. + + Gets information about the memory layer of a cluster. + + Returns: + Callable[[~.GetMemoryLayerRequest], + ~.MemoryLayer]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_memory_layer" not in self._stubs: + self._stubs["get_memory_layer"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetMemoryLayer", + request_serializer=bigtable_instance_admin.GetMemoryLayerRequest.serialize, + response_deserializer=instance.MemoryLayer.deserialize, + ) + return self._stubs["get_memory_layer"] + @property def create_app_profile( self, diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py index 7bf432d97d30..75d53dee0f7f 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/grpc_asyncio.py @@ -729,6 +729,95 @@ def delete_cluster( ) return self._stubs["delete_cluster"] + @property + def update_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMemoryLayerRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update memory layer method over gRPC. + + Updates the memory layer of a cluster. + + To enable the memory layer, set the memory_config. To disable + the memory layer, unset the memory_config. + + Returns: + Callable[[~.UpdateMemoryLayerRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_memory_layer" not in self._stubs: + self._stubs["update_memory_layer"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/UpdateMemoryLayer", + request_serializer=bigtable_instance_admin.UpdateMemoryLayerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_memory_layer"] + + @property + def list_memory_layers( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMemoryLayersRequest], + Awaitable[bigtable_instance_admin.ListMemoryLayersResponse], + ]: + r"""Return a callable for the list memory layers method over gRPC. + + Lists information about memory layers. + + Returns: + Callable[[~.ListMemoryLayersRequest], + Awaitable[~.ListMemoryLayersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_memory_layers" not in self._stubs: + self._stubs["list_memory_layers"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/ListMemoryLayers", + request_serializer=bigtable_instance_admin.ListMemoryLayersRequest.serialize, + response_deserializer=bigtable_instance_admin.ListMemoryLayersResponse.deserialize, + ) + return self._stubs["list_memory_layers"] + + @property + def get_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMemoryLayerRequest], Awaitable[instance.MemoryLayer] + ]: + r"""Return a callable for the get memory layer method over gRPC. + + Gets information about the memory layer of a cluster. + + Returns: + Callable[[~.GetMemoryLayerRequest], + Awaitable[~.MemoryLayer]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_memory_layer" not in self._stubs: + self._stubs["get_memory_layer"] = self._logged_channel.unary_unary( + "/google.bigtable.admin.v2.BigtableInstanceAdmin/GetMemoryLayer", + request_serializer=bigtable_instance_admin.GetMemoryLayerRequest.serialize, + response_deserializer=instance.MemoryLayer.deserialize, + ) + return self._stubs["get_memory_layer"] + @property def create_app_profile( self, @@ -1409,6 +1498,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.update_memory_layer: self._wrap_method( + self.update_memory_layer, + default_timeout=None, + client_info=client_info, + ), + self.list_memory_layers: self._wrap_method( + self.list_memory_layers, + default_timeout=None, + client_info=client_info, + ), + self.get_memory_layer: self._wrap_method( + self.get_memory_layer, + default_timeout=None, + client_info=client_info, + ), self.create_app_profile: self._wrap_method( self.create_app_profile, default_timeout=60.0, diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py index 897c868ae03c..2f2765309e92 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest.py @@ -184,6 +184,14 @@ def post_get_materialized_view(self, response): logging.log(f"Received response: {response}") return response + def pre_get_memory_layer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_memory_layer(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_app_profiles(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -232,6 +240,14 @@ def post_list_materialized_views(self, response): logging.log(f"Received response: {response}") return response + def pre_list_memory_layers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_memory_layers(self, response): + logging.log(f"Received response: {response}") + return response + def pre_partial_update_cluster(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -304,6 +320,14 @@ def post_update_materialized_view(self, response): logging.log(f"Received response: {response}") return response + def pre_update_memory_layer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_memory_layer(self, response): + logging.log(f"Received response: {response}") + return response + transport = BigtableInstanceAdminRestTransport(interceptor=MyCustomBigtableInstanceAdminInterceptor()) client = BigtableInstanceAdminClient(transport=transport) @@ -917,6 +941,55 @@ def post_get_materialized_view_with_metadata( """ return response, metadata + def pre_get_memory_layer( + self, + request: bigtable_instance_admin.GetMemoryLayerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.GetMemoryLayerRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_memory_layer + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_get_memory_layer( + self, response: instance.MemoryLayer + ) -> instance.MemoryLayer: + """Post-rpc interceptor for get_memory_layer + + DEPRECATED. Please use the `post_get_memory_layer_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_get_memory_layer` interceptor runs + before the `post_get_memory_layer_with_metadata` interceptor. + """ + return response + + def post_get_memory_layer_with_metadata( + self, + response: instance.MemoryLayer, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.MemoryLayer, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_memory_layer + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_get_memory_layer_with_metadata` + interceptor in new development instead of the `post_get_memory_layer` interceptor. + When both interceptors are used, this `post_get_memory_layer_with_metadata` interceptor runs after the + `post_get_memory_layer` interceptor. The (possibly modified) response returned by + `post_get_memory_layer` will be passed to + `post_get_memory_layer_with_metadata`. + """ + return response, metadata + def pre_list_app_profiles( self, request: bigtable_instance_admin.ListAppProfilesRequest, @@ -1229,6 +1302,58 @@ def post_list_materialized_views_with_metadata( """ return response, metadata + def pre_list_memory_layers( + self, + request: bigtable_instance_admin.ListMemoryLayersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListMemoryLayersRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_memory_layers + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_list_memory_layers( + self, response: bigtable_instance_admin.ListMemoryLayersResponse + ) -> bigtable_instance_admin.ListMemoryLayersResponse: + """Post-rpc interceptor for list_memory_layers + + DEPRECATED. Please use the `post_list_memory_layers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_list_memory_layers` interceptor runs + before the `post_list_memory_layers_with_metadata` interceptor. + """ + return response + + def post_list_memory_layers_with_metadata( + self, + response: bigtable_instance_admin.ListMemoryLayersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.ListMemoryLayersResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_memory_layers + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_list_memory_layers_with_metadata` + interceptor in new development instead of the `post_list_memory_layers` interceptor. + When both interceptors are used, this `post_list_memory_layers_with_metadata` interceptor runs after the + `post_list_memory_layers` interceptor. The (possibly modified) response returned by + `post_list_memory_layers` will be passed to + `post_list_memory_layers_with_metadata`. + """ + return response, metadata + def pre_partial_update_cluster( self, request: bigtable_instance_admin.PartialUpdateClusterRequest, @@ -1662,6 +1787,55 @@ def post_update_materialized_view_with_metadata( """ return response, metadata + def pre_update_memory_layer( + self, + request: bigtable_instance_admin.UpdateMemoryLayerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + bigtable_instance_admin.UpdateMemoryLayerRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_memory_layer + + Override in a subclass to manipulate the request or metadata + before they are sent to the BigtableInstanceAdmin server. + """ + return request, metadata + + def post_update_memory_layer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_memory_layer + + DEPRECATED. Please use the `post_update_memory_layer_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BigtableInstanceAdmin server but before + it is returned to user code. This `post_update_memory_layer` interceptor runs + before the `post_update_memory_layer_with_metadata` interceptor. + """ + return response + + def post_update_memory_layer_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_memory_layer + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BigtableInstanceAdmin server but before it is returned to user code. + + We recommend only using this `post_update_memory_layer_with_metadata` + interceptor in new development instead of the `post_update_memory_layer` interceptor. + When both interceptors are used, this `post_update_memory_layer_with_metadata` interceptor runs after the + `post_update_memory_layer` interceptor. The (possibly modified) response returned by + `post_update_memory_layer` will be passed to + `post_update_memory_layer_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class BigtableInstanceAdminRestStub: @@ -4078,6 +4252,157 @@ def __call__( ) return resp + class _GetMemoryLayer( + _BaseBigtableInstanceAdminRestTransport._BaseGetMemoryLayer, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.GetMemoryLayer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.GetMemoryLayerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.MemoryLayer: + r"""Call the get memory layer method over HTTP. + + Args: + request (~.bigtable_instance_admin.GetMemoryLayerRequest): + The request object. Request message for + BigtableInstanceAdmin.GetMemoryLayer. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.instance.MemoryLayer: + The memory layer of a cluster. A + memory layer serves reads from memory + without hitting the backing persistent + data store. + + """ + + http_options = _BaseBigtableInstanceAdminRestTransport._BaseGetMemoryLayer._get_http_options() + request, metadata = self._interceptor.pre_get_memory_layer( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBigtableInstanceAdminRestTransport._BaseGetMemoryLayer, + "_BaseGetMemoryLayer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.GetMemoryLayer", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetMemoryLayer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BigtableInstanceAdminRestTransport._GetMemoryLayer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = instance.MemoryLayer() + pb_resp = instance.MemoryLayer.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_memory_layer(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_memory_layer_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.MemoryLayer.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.get_memory_layer", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "GetMemoryLayer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ListAppProfiles( _BaseBigtableInstanceAdminRestTransport._BaseListAppProfiles, BigtableInstanceAdminRestStub, @@ -4992,12 +5317,12 @@ def __call__( ) return resp - class _PartialUpdateCluster( - _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateCluster, + class _ListMemoryLayers( + _BaseBigtableInstanceAdminRestTransport._BaseListMemoryLayers, BigtableInstanceAdminRestStub, ): def __hash__(self): - return hash("BigtableInstanceAdminRestTransport.PartialUpdateCluster") + return hash("BigtableInstanceAdminRestTransport.ListMemoryLayers") @staticmethod def _get_response( @@ -5018,24 +5343,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: bigtable_instance_admin.PartialUpdateClusterRequest, + request: bigtable_instance_admin.ListMemoryLayersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the partial update cluster method over HTTP. + ) -> bigtable_instance_admin.ListMemoryLayersResponse: + r"""Call the list memory layers method over HTTP. Args: - request (~.bigtable_instance_admin.PartialUpdateClusterRequest): + request (~.bigtable_instance_admin.ListMemoryLayersRequest): The request object. Request message for - BigtableInstanceAdmin.PartialUpdateCluster. + BigtableInstanceAdmin.ListMemoryLayers. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5045,23 +5369,22 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.bigtable_instance_admin.ListMemoryLayersResponse: + Response message for + BigtableInstanceAdmin.ListMemoryLayers. """ - http_options = _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateCluster._get_http_options() - request, metadata = self._interceptor.pre_partial_update_cluster( + http_options = _BaseBigtableInstanceAdminRestTransport._BaseListMemoryLayers._get_http_options() + request, metadata = self._interceptor.pre_list_memory_layers( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateCluster, - "_BasePartialUpdateCluster__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBigtableInstanceAdminRestTransport._BaseListMemoryLayers, + "_BaseListMemoryLayers__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5085,10 +5408,10 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.PartialUpdateCluster", + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.ListMemoryLayers", extra={ "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", - "rpcName": "PartialUpdateCluster", + "rpcName": "ListMemoryLayers", "httpRequest": http_request, "metadata": http_request["headers"], }, @@ -5096,14 +5419,13 @@ def __call__( # Send the request response = ( - BigtableInstanceAdminRestTransport._PartialUpdateCluster._get_response( + BigtableInstanceAdminRestTransport._ListMemoryLayers._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) ) @@ -5113,7 +5435,165 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() + resp = bigtable_instance_admin.ListMemoryLayersResponse() + pb_resp = bigtable_instance_admin.ListMemoryLayersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_memory_layers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_memory_layers_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + bigtable_instance_admin.ListMemoryLayersResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.list_memory_layers", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "ListMemoryLayers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PartialUpdateCluster( + _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateCluster, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.PartialUpdateCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.PartialUpdateClusterRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the partial update cluster method over HTTP. + + Args: + request (~.bigtable_instance_admin.PartialUpdateClusterRequest): + The request object. Request message for + BigtableInstanceAdmin.PartialUpdateCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateCluster._get_http_options() + request, metadata = self._interceptor.pre_partial_update_cluster( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBigtableInstanceAdminRestTransport._BasePartialUpdateCluster, + "_BasePartialUpdateCluster__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.PartialUpdateCluster", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "PartialUpdateCluster", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BigtableInstanceAdminRestTransport._PartialUpdateCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) resp = self._interceptor.post_partial_update_cluster(resp) @@ -6428,6 +6908,158 @@ def __call__( ) return resp + class _UpdateMemoryLayer( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateMemoryLayer, + BigtableInstanceAdminRestStub, + ): + def __hash__(self): + return hash("BigtableInstanceAdminRestTransport.UpdateMemoryLayer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: bigtable_instance_admin.UpdateMemoryLayerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update memory layer method over HTTP. + + Args: + request (~.bigtable_instance_admin.UpdateMemoryLayerRequest): + The request object. Request message for + BigtableInstanceAdmin.UpdateMemoryLayer. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBigtableInstanceAdminRestTransport._BaseUpdateMemoryLayer._get_http_options() + request, metadata = self._interceptor.pre_update_memory_layer( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBigtableInstanceAdminRestTransport._BaseUpdateMemoryLayer, + "_BaseUpdateMemoryLayer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.bigtable.admin_v2.BigtableInstanceAdminClient.UpdateMemoryLayer", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateMemoryLayer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BigtableInstanceAdminRestTransport._UpdateMemoryLayer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_memory_layer(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_memory_layer_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.bigtable.admin_v2.BigtableInstanceAdminClient.update_memory_layer", + extra={ + "serviceName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "rpcName": "UpdateMemoryLayer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def create_app_profile( self, @@ -6577,6 +7209,16 @@ def get_materialized_view( # In C++ this would require a dynamic_cast return self._GetMaterializedView(self._session, self._host, self._interceptor) # type: ignore + @property + def get_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.GetMemoryLayerRequest], instance.MemoryLayer + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMemoryLayer(self._session, self._host, self._interceptor) # type: ignore + @property def list_app_profiles( self, @@ -6643,6 +7285,17 @@ def list_materialized_views( # In C++ this would require a dynamic_cast return self._ListMaterializedViews(self._session, self._host, self._interceptor) # type: ignore + @property + def list_memory_layers( + self, + ) -> Callable[ + [bigtable_instance_admin.ListMemoryLayersRequest], + bigtable_instance_admin.ListMemoryLayersResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMemoryLayers(self._session, self._host, self._interceptor) # type: ignore + @property def partial_update_cluster( self, @@ -6727,6 +7380,16 @@ def update_materialized_view( self._session, self._host, self._interceptor ) # type: ignore + @property + def update_memory_layer( + self, + ) -> Callable[ + [bigtable_instance_admin.UpdateMemoryLayerRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMemoryLayer(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py index 2335cdaa5615..9972a1b35562 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/services/bigtable_instance_admin/transports/rest_base.py @@ -373,6 +373,22 @@ def _get_http_options(): ] return http_options + class _BaseGetMemoryLayer: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/instances/*/clusters/*/memoryLayer}", + }, + ] + return http_options + class _BaseListAppProfiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -469,6 +485,22 @@ def _get_http_options(): ] return http_options + class _BaseListMemoryLayers: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/instances/*/clusters/*}/memoryLayers", + }, + ] + return http_options + class _BasePartialUpdateCluster: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -646,5 +678,22 @@ def _get_http_options(): ] return http_options + class _BaseUpdateMemoryLayer: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{memory_layer.name=projects/*/instances/*/clusters/*/memoryLayer}", + "body": "memory_layer", + }, + ] + return http_options + __all__ = ("_BaseBigtableInstanceAdminRestTransport",) diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/__init__.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/__init__.py index 7ddc8cdce975..5ed4bf678f9c 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/__init__.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/__init__.py @@ -33,6 +33,7 @@ GetInstanceRequest, GetLogicalViewRequest, GetMaterializedViewRequest, + GetMemoryLayerRequest, ListAppProfilesRequest, ListAppProfilesResponse, ListClustersRequest, @@ -45,6 +46,8 @@ ListLogicalViewsResponse, ListMaterializedViewsRequest, ListMaterializedViewsResponse, + ListMemoryLayersRequest, + ListMemoryLayersResponse, PartialUpdateClusterMetadata, PartialUpdateClusterRequest, PartialUpdateInstanceRequest, @@ -56,6 +59,8 @@ UpdateLogicalViewRequest, UpdateMaterializedViewMetadata, UpdateMaterializedViewRequest, + UpdateMemoryLayerMetadata, + UpdateMemoryLayerRequest, ) from .bigtable_table_admin import ( CheckConsistencyRequest, @@ -125,6 +130,7 @@ Instance, LogicalView, MaterializedView, + MemoryLayer, ) from .table import ( AuthorizedView, @@ -168,6 +174,7 @@ "GetInstanceRequest", "GetLogicalViewRequest", "GetMaterializedViewRequest", + "GetMemoryLayerRequest", "ListAppProfilesRequest", "ListAppProfilesResponse", "ListClustersRequest", @@ -180,6 +187,8 @@ "ListLogicalViewsResponse", "ListMaterializedViewsRequest", "ListMaterializedViewsResponse", + "ListMemoryLayersRequest", + "ListMemoryLayersResponse", "PartialUpdateClusterMetadata", "PartialUpdateClusterRequest", "PartialUpdateInstanceRequest", @@ -191,6 +200,8 @@ "UpdateLogicalViewRequest", "UpdateMaterializedViewMetadata", "UpdateMaterializedViewRequest", + "UpdateMemoryLayerMetadata", + "UpdateMemoryLayerRequest", "CheckConsistencyRequest", "CheckConsistencyResponse", "CopyBackupMetadata", @@ -254,6 +265,7 @@ "Instance", "LogicalView", "MaterializedView", + "MemoryLayer", "AuthorizedView", "AvroSchema", "Backup", diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py index 442d6878ef72..2fd5ac847229 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py @@ -43,6 +43,11 @@ "UpdateClusterMetadata", "PartialUpdateClusterMetadata", "PartialUpdateClusterRequest", + "UpdateMemoryLayerRequest", + "UpdateMemoryLayerMetadata", + "ListMemoryLayersRequest", + "ListMemoryLayersResponse", + "GetMemoryLayerRequest", "CreateAppProfileRequest", "GetAppProfileRequest", "ListAppProfilesRequest", @@ -614,6 +619,156 @@ class PartialUpdateClusterRequest(proto.Message): ) +class UpdateMemoryLayerRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.UpdateMemoryLayer. + + Attributes: + memory_layer (google.cloud.bigtable_admin_v2.types.MemoryLayer): + Required. The memory layer to update. + + The memory layer's ``name`` format is as follows: + ``projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + memory_layer: gba_instance.MemoryLayer = proto.Field( + proto.MESSAGE, + number=1, + message=gba_instance.MemoryLayer, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateMemoryLayerMetadata(proto.Message): + r"""The metadata for the Operation returned by UpdateMemoryLayer. + + Attributes: + original_request (google.cloud.bigtable_admin_v2.types.UpdateMemoryLayerRequest): + The request that prompted the initiation of + this UpdateMemoryLayer operation. + request_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the original request was + received. + finish_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the operation failed or was + completed successfully. + """ + + original_request: "UpdateMemoryLayerRequest" = proto.Field( + proto.MESSAGE, + number=1, + message="UpdateMemoryLayerRequest", + ) + request_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + finish_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ListMemoryLayersRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.ListMemoryLayers. + + Attributes: + parent (str): + Required. The unique name of the cluster for which a list of + memory layers is requested. Values are of the form + ``projects/{project}/instances/{instance}/clusters/{cluster}``. + Use ``{cluster} = '-'`` to list MemoryLayers for all + Clusters in an instance, e.g., + ``projects/myproject/instances/myinstance/clusters/-``. + page_size (int): + Optional. The maximum number of memory layers + to return. The service may return fewer than + this value. + page_token (str): + Optional. A page token, received from a previous + ``ListMemoryLayers`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListMemoryLayers`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMemoryLayersResponse(proto.Message): + r"""Response message for BigtableInstanceAdmin.ListMemoryLayers. + + Attributes: + memory_layers (MutableSequence[google.cloud.bigtable_admin_v2.types.MemoryLayer]): + The list of requested memory layers. + failed_locations (MutableSequence[str]): + Locations from which MemoryLayer information could not be + retrieved, due to an outage or some other transient + condition. MemoryLayers from these locations may be missing + from ``memory_layers``, or may only have partial information + returned. Values are of the form + ``projects//locations/`` + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + memory_layers: MutableSequence[gba_instance.MemoryLayer] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gba_instance.MemoryLayer, + ) + failed_locations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetMemoryLayerRequest(proto.Message): + r"""Request message for BigtableInstanceAdmin.GetMemoryLayer. + + Attributes: + name (str): + Required. The unique name of the requested cluster's memory + layer. Values are of the form + ``projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class CreateAppProfileRequest(proto.Message): r"""Request message for BigtableInstanceAdmin.CreateAppProfile. diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/instance.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/instance.py index f142afab161b..19d0c25e8122 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/instance.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/instance.py @@ -29,6 +29,7 @@ "AutoscalingTargets", "AutoscalingLimits", "Cluster", + "MemoryLayer", "AppProfile", "HotTablet", "LogicalView", @@ -487,6 +488,99 @@ class EncryptionConfig(proto.Message): ) +class MemoryLayer(proto.Message): + r"""The memory layer of a cluster. A memory layer serves reads + from memory without hitting the backing persistent data store. + + Attributes: + name (str): + Identifier. Name of the memory layer. This is + always: + "projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer". + memory_config (google.cloud.bigtable_admin_v2.types.MemoryLayer.MemoryConfig): + The configuration of this memory layer. Set an empty + ``memory_config`` to enable the memory layer. Unset this to + disable the memory layer. + etag (str): + Optional. The etag for this memory layer. + This may be sent on update requests to ensure + that the client has an up-to-date value before + proceeding. The server returns an ABORTED error + on a mismatched etag. + state (google.cloud.bigtable_admin_v2.types.MemoryLayer.State): + Output only. The current state of the memory + layer. + """ + + class State(proto.Enum): + r"""Possible states of a memory layer. + + Values: + STATE_NOT_KNOWN (0): + The state of the memory layer could not be + determined. + READY (1): + The memory layer has been successfully + enabled and is ready to serve requests. + ENABLING (2): + The memory layer is currently being enabled, + and may be disabled if the enablement process + encounters an error. A cluster may not be able + to serve requests from the memory layer while + being enabled. + RESIZING (3): + The memory layer is currently being resized, + and may revert to its previous storage size if + the process encounters an error. The memory + layer is still capable of serving requests while + being resized, but may exhibit performance as if + its number of allocated nodes is between the + starting and requested states. + DISABLED (4): + The memory layer is disabled. The default + state for a cluster without a memory layer. + """ + + STATE_NOT_KNOWN = 0 + READY = 1 + ENABLING = 2 + RESIZING = 3 + DISABLED = 4 + + class MemoryConfig(proto.Message): + r"""Configuration of a memory layer. + + Attributes: + storage_size_gib (int): + Output only. Reporting the current size of + the memory layer in GiB. + """ + + storage_size_gib: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + memory_config: MemoryConfig = proto.Field( + proto.MESSAGE, + number=2, + message=MemoryConfig, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + + class AppProfile(proto.Message): r"""A configuration object describing how Cloud Bigtable should treat traffic from a particular end user application. @@ -649,13 +743,31 @@ class StandardIsolation(proto.Message): priority (google.cloud.bigtable_admin_v2.types.AppProfile.Priority): The priority of requests sent using this app profile. + memory_config (google.cloud.bigtable_admin_v2.types.AppProfile.StandardIsolation.MemoryConfig): + Optional. The memory config to use for + requests sent using this app profile. """ + class MemoryConfig(proto.Message): + r"""If set, eligible single-row requests (currently limited to + ReadRows) using this app profile will be routed to the memory + layer. All eligible writes populate the memory layer. + MemoryConfig can only be set if the AppProfile uses single + cluster routing and the configured cluster has a memory layer + enabled. + + """ + priority: "AppProfile.Priority" = proto.Field( proto.ENUM, number=1, enum="AppProfile.Priority", ) + memory_config: "AppProfile.StandardIsolation.MemoryConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="AppProfile.StandardIsolation.MemoryConfig", + ) class DataBoostIsolationReadOnly(proto.Message): r"""Data Boost is a serverless compute capability that lets you diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_v2/gapic_version.py b/packages/google-cloud-bigtable/google/cloud/bigtable_v2/gapic_version.py index 80808e348d78..47a60f03e311 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_v2/gapic_version.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.45.0" # {x-release-please-version} +__version__ = "2.46.0" # {x-release-please-version} diff --git a/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_async.py b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_async.py new file mode 100644 index 000000000000..175d3365ae98 --- /dev/null +++ b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMemoryLayer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigtable + + +# [START bigtableadmin_v2_generated_BigtableInstanceAdmin_GetMemoryLayer_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import bigtable_admin_v2 + + +async def sample_get_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminAsyncClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.GetMemoryLayerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_memory_layer(request=request) + + # Handle the response + print(response) + + +# [END bigtableadmin_v2_generated_BigtableInstanceAdmin_GetMemoryLayer_async] diff --git a/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_sync.py b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_sync.py new file mode 100644 index 000000000000..193741ed1407 --- /dev/null +++ b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMemoryLayer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigtable + + +# [START bigtableadmin_v2_generated_BigtableInstanceAdmin_GetMemoryLayer_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import bigtable_admin_v2 + + +def sample_get_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.GetMemoryLayerRequest( + name="name_value", + ) + + # Make the request + response = client.get_memory_layer(request=request) + + # Handle the response + print(response) + + +# [END bigtableadmin_v2_generated_BigtableInstanceAdmin_GetMemoryLayer_sync] diff --git a/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_async.py b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_async.py new file mode 100644 index 000000000000..0b5c7d0071e9 --- /dev/null +++ b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMemoryLayers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigtable + + +# [START bigtableadmin_v2_generated_BigtableInstanceAdmin_ListMemoryLayers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import bigtable_admin_v2 + + +async def sample_list_memory_layers(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminAsyncClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.ListMemoryLayersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memory_layers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END bigtableadmin_v2_generated_BigtableInstanceAdmin_ListMemoryLayers_async] diff --git a/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_sync.py b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_sync.py new file mode 100644 index 000000000000..f68741d6cddb --- /dev/null +++ b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMemoryLayers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigtable + + +# [START bigtableadmin_v2_generated_BigtableInstanceAdmin_ListMemoryLayers_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import bigtable_admin_v2 + + +def sample_list_memory_layers(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.ListMemoryLayersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memory_layers(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END bigtableadmin_v2_generated_BigtableInstanceAdmin_ListMemoryLayers_sync] diff --git a/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_async.py b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_async.py new file mode 100644 index 000000000000..0b4d21b263a1 --- /dev/null +++ b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMemoryLayer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigtable + + +# [START bigtableadmin_v2_generated_BigtableInstanceAdmin_UpdateMemoryLayer_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import bigtable_admin_v2 + + +async def sample_update_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminAsyncClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.UpdateMemoryLayerRequest() + + # Make the request + operation = await client.update_memory_layer(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END bigtableadmin_v2_generated_BigtableInstanceAdmin_UpdateMemoryLayer_async] diff --git a/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_sync.py b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_sync.py new file mode 100644 index 000000000000..2745d2d1360b --- /dev/null +++ b/packages/google-cloud-bigtable/samples/generated_samples/bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMemoryLayer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigtable + + +# [START bigtableadmin_v2_generated_BigtableInstanceAdmin_UpdateMemoryLayer_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import bigtable_admin_v2 + + +def sample_update_memory_layer(): + # Create a client + client = bigtable_admin_v2.BigtableInstanceAdminClient() + + # Initialize request argument(s) + request = bigtable_admin_v2.UpdateMemoryLayerRequest() + + # Make the request + operation = client.update_memory_layer(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END bigtableadmin_v2_generated_BigtableInstanceAdmin_UpdateMemoryLayer_sync] diff --git a/packages/google-cloud-bigtable/samples/generated_samples/snippet_metadata_google.bigtable.admin.v2.json b/packages/google-cloud-bigtable/samples/generated_samples/snippet_metadata_google.bigtable.admin.v2.json index 18eb4108003f..980fa928e5d9 100644 --- a/packages/google-cloud-bigtable/samples/generated_samples/snippet_metadata_google.bigtable.admin.v2.json +++ b/packages/google-cloud-bigtable/samples/generated_samples/snippet_metadata_google.bigtable.admin.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigtable", - "version": "2.45.0" + "version": "2.46.0" }, "snippets": [ { @@ -2653,6 +2653,167 @@ ], "title": "bigtableadmin_v2_generated_bigtable_instance_admin_get_materialized_view_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminAsyncClient", + "shortName": "BigtableInstanceAdminAsyncClient" + }, + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminAsyncClient.get_memory_layer", + "method": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin.GetMemoryLayer", + "service": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "shortName": "BigtableInstanceAdmin" + }, + "shortName": "GetMemoryLayer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigtable_admin_v2.types.GetMemoryLayerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.bigtable_admin_v2.types.MemoryLayer", + "shortName": "get_memory_layer" + }, + "description": "Sample for GetMemoryLayer", + "file": "bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigtableadmin_v2_generated_BigtableInstanceAdmin_GetMemoryLayer_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminClient", + "shortName": "BigtableInstanceAdminClient" + }, + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminClient.get_memory_layer", + "method": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin.GetMemoryLayer", + "service": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "shortName": "BigtableInstanceAdmin" + }, + "shortName": "GetMemoryLayer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigtable_admin_v2.types.GetMemoryLayerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.bigtable_admin_v2.types.MemoryLayer", + "shortName": "get_memory_layer" + }, + "description": "Sample for GetMemoryLayer", + "file": "bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigtableadmin_v2_generated_BigtableInstanceAdmin_GetMemoryLayer_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigtableadmin_v2_generated_bigtable_instance_admin_get_memory_layer_sync.py" + }, { "canonical": true, "clientMethod": { @@ -3619,6 +3780,167 @@ ], "title": "bigtableadmin_v2_generated_bigtable_instance_admin_list_materialized_views_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminAsyncClient", + "shortName": "BigtableInstanceAdminAsyncClient" + }, + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminAsyncClient.list_memory_layers", + "method": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin.ListMemoryLayers", + "service": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "shortName": "BigtableInstanceAdmin" + }, + "shortName": "ListMemoryLayers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigtable_admin_v2.types.ListMemoryLayersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListMemoryLayersAsyncPager", + "shortName": "list_memory_layers" + }, + "description": "Sample for ListMemoryLayers", + "file": "bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigtableadmin_v2_generated_BigtableInstanceAdmin_ListMemoryLayers_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminClient", + "shortName": "BigtableInstanceAdminClient" + }, + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminClient.list_memory_layers", + "method": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin.ListMemoryLayers", + "service": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "shortName": "BigtableInstanceAdmin" + }, + "shortName": "ListMemoryLayers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigtable_admin_v2.types.ListMemoryLayersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.pagers.ListMemoryLayersPager", + "shortName": "list_memory_layers" + }, + "description": "Sample for ListMemoryLayers", + "file": "bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigtableadmin_v2_generated_BigtableInstanceAdmin_ListMemoryLayers_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigtableadmin_v2_generated_bigtable_instance_admin_list_memory_layers_sync.py" + }, { "canonical": true, "clientMethod": { @@ -5100,6 +5422,175 @@ ], "title": "bigtableadmin_v2_generated_bigtable_instance_admin_update_materialized_view_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminAsyncClient", + "shortName": "BigtableInstanceAdminAsyncClient" + }, + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminAsyncClient.update_memory_layer", + "method": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin.UpdateMemoryLayer", + "service": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "shortName": "BigtableInstanceAdmin" + }, + "shortName": "UpdateMemoryLayer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigtable_admin_v2.types.UpdateMemoryLayerRequest" + }, + { + "name": "memory_layer", + "type": "google.cloud.bigtable_admin_v2.types.MemoryLayer" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_memory_layer" + }, + "description": "Sample for UpdateMemoryLayer", + "file": "bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigtableadmin_v2_generated_BigtableInstanceAdmin_UpdateMemoryLayer_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminClient", + "shortName": "BigtableInstanceAdminClient" + }, + "fullName": "google.cloud.bigtable_admin_v2.BigtableInstanceAdminClient.update_memory_layer", + "method": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin.UpdateMemoryLayer", + "service": { + "fullName": "google.bigtable.admin.v2.BigtableInstanceAdmin", + "shortName": "BigtableInstanceAdmin" + }, + "shortName": "UpdateMemoryLayer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigtable_admin_v2.types.UpdateMemoryLayerRequest" + }, + { + "name": "memory_layer", + "type": "google.cloud.bigtable_admin_v2.types.MemoryLayer" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_memory_layer" + }, + "description": "Sample for UpdateMemoryLayer", + "file": "bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigtableadmin_v2_generated_BigtableInstanceAdmin_UpdateMemoryLayer_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigtableadmin_v2_generated_bigtable_instance_admin_update_memory_layer_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-bigtable/tests/system/v2_client/test_data_api.py b/packages/google-cloud-bigtable/tests/system/v2_client/test_data_api.py index 4e5d3f5e7387..72be2192f1b7 100644 --- a/packages/google-cloud-bigtable/tests/system/v2_client/test_data_api.py +++ b/packages/google-cloud-bigtable/tests/system/v2_client/test_data_api.py @@ -725,6 +725,27 @@ def _assert_data_table_read_rows_retry_correct(rows_data): ) +def test_table_read_rows_multiple_reads( + data_table_read_rows_retry_tests, +): + from types import SimpleNamespace + + rows_data = data_table_read_rows_retry_tests.read_rows() + first_iteration = SimpleNamespace() + first_iteration.rows = {} + + second_iteration = SimpleNamespace() + second_iteration.rows = {} + for item in rows_data: + first_iteration.rows[item.row_key] = item + + for item in rows_data: + second_iteration.rows[item.row_key] = item + + _assert_data_table_read_rows_retry_correct(first_iteration) + assert second_iteration.rows == {} + + def test_table_read_rows_retry_unretriable_error_establishing_stream( data_table_read_rows_retry_tests, ): @@ -732,11 +753,12 @@ def test_table_read_rows_retry_unretriable_error_establishing_stream( error_injector = data_table_read_rows_retry_tests.error_injector error_injector.errors_to_inject = [ - error_injector.make_exception(StatusCode.ABORTED, fail_mid_stream=False) + error_injector.make_exception(StatusCode.DATA_LOSS, fail_mid_stream=False) ] - with pytest.raises(exceptions.Aborted): - data_table_read_rows_retry_tests.read_rows() + rows_data = data_table_read_rows_retry_tests.read_rows() + with pytest.raises(exceptions.DataLoss): + rows_data.consume_all() def test_table_read_rows_retry_retriable_error_establishing_stream( @@ -797,25 +819,25 @@ def test_table_read_rows_retry_retriable_errors_mid_stream( def test_table_read_rows_retry_retriable_internal_errors_mid_stream( data_table_read_rows_retry_tests, ): - from google.cloud.bigtable.row_data import RETRYABLE_INTERNAL_ERROR_MESSAGES + from google.cloud.bigtable.data._helpers import _RETRYABLE_INTERNAL_ERROR_MESSAGES error_injector = data_table_read_rows_retry_tests.error_injector error_injector.errors_to_inject = [ error_injector.make_exception( StatusCode.INTERNAL, - message=RETRYABLE_INTERNAL_ERROR_MESSAGES[0], + message=_RETRYABLE_INTERNAL_ERROR_MESSAGES[0], fail_mid_stream=True, successes_before_fail=2, ), error_injector.make_exception( StatusCode.INTERNAL, - message=RETRYABLE_INTERNAL_ERROR_MESSAGES[1], + message=_RETRYABLE_INTERNAL_ERROR_MESSAGES[1], fail_mid_stream=True, successes_before_fail=1, ), error_injector.make_exception( StatusCode.INTERNAL, - message=RETRYABLE_INTERNAL_ERROR_MESSAGES[2], + message=_RETRYABLE_INTERNAL_ERROR_MESSAGES[2], fail_mid_stream=True, successes_before_fail=0, ), @@ -858,12 +880,12 @@ def test_table_read_rows_retry_retriable_error_mid_stream_unretriable_error_rees error_injector.make_exception( StatusCode.UNAVAILABLE, fail_mid_stream=True, successes_before_fail=5 ), - error_injector.make_exception(StatusCode.ABORTED, fail_mid_stream=False), + error_injector.make_exception(StatusCode.DATA_LOSS, fail_mid_stream=False), ] rows_data = data_table_read_rows_retry_tests.read_rows() - with pytest.raises(exceptions.Aborted): + with pytest.raises(exceptions.DataLoss): rows_data.consume_all() @@ -894,29 +916,32 @@ def test_table_read_rows_retry_timeout_mid_stream( from google.api_core import exceptions + from google.cloud.bigtable.data._helpers import _RETRYABLE_INTERNAL_ERROR_MESSAGES from google.cloud.bigtable.row_data import ( DEFAULT_RETRY_READ_ROWS, - RETRYABLE_INTERNAL_ERROR_MESSAGES, ) error_injector = data_table_read_rows_retry_tests.error_injector error_injector.errors_to_inject = [ error_injector.make_exception( StatusCode.INTERNAL, - message=RETRYABLE_INTERNAL_ERROR_MESSAGES[0], + message=_RETRYABLE_INTERNAL_ERROR_MESSAGES[0], fail_mid_stream=True, successes_before_fail=5, ), ] + [ error_injector.make_exception( StatusCode.INTERNAL, - message=RETRYABLE_INTERNAL_ERROR_MESSAGES[0], + message=_RETRYABLE_INTERNAL_ERROR_MESSAGES[0], fail_mid_stream=True, successes_before_fail=0, ), ] * 20 # Shorten the deadline so the timeout test is shorter. + data_table_read_rows_retry_tests._table_impl.default_read_rows_operation_timeout = ( + 10.0 + ) rows_data = data_table_read_rows_retry_tests.read_rows( retry=DEFAULT_RETRY_READ_ROWS.with_deadline(10.0) ) @@ -945,10 +970,14 @@ def test_table_read_rows_retry_timeout_establishing_stream( ] * 20 # Shorten the deadline so the timeout test is shorter. + data_table_read_rows_retry_tests._table_impl.default_read_rows_operation_timeout = ( + 10.0 + ) + rows_data = data_table_read_rows_retry_tests.read_rows( + retry=DEFAULT_RETRY_READ_ROWS.with_deadline(10.0) + ) with pytest.raises(exceptions.RetryError): - data_table_read_rows_retry_tests.read_rows( - retry=DEFAULT_RETRY_READ_ROWS.with_deadline(10.0) - ) + rows_data.consume_all() def test_table_check_and_mutate_rows(data_table, rows_to_delete): diff --git a/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py b/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py index 815f26a367e3..7f7e45209313 100644 --- a/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py +++ b/packages/google-cloud-bigtable/tests/unit/data/_async/test_client.py @@ -1510,49 +1510,56 @@ def test_table_ctor_sync(self): @CrossSync.pytest # iterate over all retryable rpcs @pytest.mark.parametrize( - "fn_name,fn_args,is_stream,extra_retryables", + "fn_name,fn_args,is_read_rows_fn,is_stream,extra_retryables", [ ( "read_rows_stream", (ReadRowsQuery(),), True, + True, (), ), ( "read_rows", (ReadRowsQuery(),), True, + True, (), ), ( "read_row", (b"row_key",), True, + True, (), ), ( "read_rows_sharded", ([ReadRowsQuery()],), True, + True, (), ), ( "row_exists", (b"row_key",), True, + True, (), ), - ("sample_row_keys", (), False, ()), + ("sample_row_keys", (), False, False, ()), ( "mutate_row", (b"row_key", [DeleteAllFromRow()]), False, + False, (), ), ( "bulk_mutate_rows", ([mutations.RowMutationEntry(b"key", [DeleteAllFromRow()])],), False, + False, (_MutateRowsIncomplete,), ), ], @@ -1588,6 +1595,7 @@ async def test_customizable_retryable_errors( expected_retryables, fn_name, fn_args, + is_read_rows_fn, is_stream, extra_retryables, ): @@ -1600,8 +1608,18 @@ async def test_customizable_retryable_errors( retry_fn += "_stream" if CrossSync.is_async: retry_fn = f"CrossSync.{retry_fn}" + subpackage = "_async" else: retry_fn = f"CrossSync._Sync_Impl.{retry_fn}" + subpackage = "_sync_autogen" + + # Read Rows has its own custom predicate builder that also takes in + # a list of exceptions + if is_read_rows_fn: + predicate_builder = f"google.cloud.bigtable.data.{subpackage}._read_rows._rst_stream_aware_predicate" + else: + predicate_builder = "google.api_core.retry.if_exception_type" + with mock.patch( f"google.cloud.bigtable.data._cross_sync.{retry_fn}" ) as retry_fn_mock: @@ -1609,9 +1627,7 @@ async def test_customizable_retryable_errors( table = client.get_table("instance-id", "table-id") expected_predicate = expected_retryables.__contains__ retry_fn_mock.side_effect = RuntimeError("stop early") - with mock.patch( - "google.api_core.retry.if_exception_type" - ) as predicate_builder_mock: + with mock.patch(predicate_builder) as predicate_builder_mock: predicate_builder_mock.return_value = expected_predicate with pytest.raises(Exception): # we expect an exception from attempting to call the mock diff --git a/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py b/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py index 08d628f4aef7..899041e3055c 100644 --- a/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py +++ b/packages/google-cloud-bigtable/tests/unit/data/_sync_autogen/test_client.py @@ -1263,19 +1263,20 @@ def test_ctor_invalid_timeout_values(self): client.close() @pytest.mark.parametrize( - "fn_name,fn_args,is_stream,extra_retryables", + "fn_name,fn_args,is_read_rows_fn,is_stream,extra_retryables", [ - ("read_rows_stream", (ReadRowsQuery(),), True, ()), - ("read_rows", (ReadRowsQuery(),), True, ()), - ("read_row", (b"row_key",), True, ()), - ("read_rows_sharded", ([ReadRowsQuery()],), True, ()), - ("row_exists", (b"row_key",), True, ()), - ("sample_row_keys", (), False, ()), - ("mutate_row", (b"row_key", [DeleteAllFromRow()]), False, ()), + ("read_rows_stream", (ReadRowsQuery(),), True, True, ()), + ("read_rows", (ReadRowsQuery(),), True, True, ()), + ("read_row", (b"row_key",), True, True, ()), + ("read_rows_sharded", ([ReadRowsQuery()],), True, True, ()), + ("row_exists", (b"row_key",), True, True, ()), + ("sample_row_keys", (), False, False, ()), + ("mutate_row", (b"row_key", [DeleteAllFromRow()]), False, False, ()), ( "bulk_mutate_rows", ([mutations.RowMutationEntry(b"key", [DeleteAllFromRow()])],), False, + False, (_MutateRowsIncomplete,), ), ], @@ -1310,6 +1311,7 @@ def test_customizable_retryable_errors( expected_retryables, fn_name, fn_args, + is_read_rows_fn, is_stream, extra_retryables, ): @@ -1319,6 +1321,11 @@ def test_customizable_retryable_errors( if is_stream: retry_fn += "_stream" retry_fn = f"CrossSync._Sync_Impl.{retry_fn}" + subpackage = "_sync_autogen" + if is_read_rows_fn: + predicate_builder = f"google.cloud.bigtable.data.{subpackage}._read_rows._rst_stream_aware_predicate" + else: + predicate_builder = "google.api_core.retry.if_exception_type" with mock.patch( f"google.cloud.bigtable.data._cross_sync.{retry_fn}" ) as retry_fn_mock: @@ -1326,9 +1333,7 @@ def test_customizable_retryable_errors( table = client.get_table("instance-id", "table-id") expected_predicate = expected_retryables.__contains__ retry_fn_mock.side_effect = RuntimeError("stop early") - with mock.patch( - "google.api_core.retry.if_exception_type" - ) as predicate_builder_mock: + with mock.patch(predicate_builder) as predicate_builder_mock: predicate_builder_mock.return_value = expected_predicate with pytest.raises(Exception): test_fn = table.__getattribute__(fn_name) diff --git a/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py b/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py index 289b5ba7408b..ef65b5f30625 100644 --- a/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py +++ b/packages/google-cloud-bigtable/tests/unit/data/test__helpers.py @@ -222,6 +222,48 @@ def test_get_timeouts_invalid(self, input_times): _helpers._align_timeouts(input_times[0], input_times[1]) +class TestRstStreamAwarePredicate: + @pytest.mark.parametrize( + "retryable_exceptions,exception,expected_is_retryable", + [ + ( + [core_exceptions.Aborted, core_exceptions.InternalServerError], + core_exceptions.InternalServerError("Sorry"), + True, + ), + ( + [core_exceptions.Aborted, core_exceptions.InternalServerError], + core_exceptions.DataLoss("Sorry"), + False, + ), + ( + [core_exceptions.ServiceUnavailable, core_exceptions.Aborted], + core_exceptions.InternalServerError("Sorry"), + False, + ), + ( + [core_exceptions.ServiceUnavailable, core_exceptions.Aborted], + core_exceptions.InternalServerError( + _helpers._RETRYABLE_INTERNAL_ERROR_MESSAGES[0] + ), + True, + ), + ( + [core_exceptions.InternalServerError, core_exceptions.Aborted], + core_exceptions.InternalServerError( + _helpers._RETRYABLE_INTERNAL_ERROR_MESSAGES[0] + ), + True, + ), + ], + ) + def test_rst_stream_aware_predicate( + self, retryable_exceptions, exception, expected_is_retryable + ): + predicate = _helpers._rst_stream_aware_predicate(*retryable_exceptions) + assert predicate(exception) is expected_is_retryable + + class TestGetRetryableErrors: @pytest.mark.parametrize( "input_codes,input_table,expected", diff --git a/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py b/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py index 9796044d1ec9..1fde876c25f0 100644 --- a/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py +++ b/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_instance_admin.py @@ -5042,11 +5042,11 @@ async def test_delete_cluster_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateAppProfileRequest(), + bigtable_instance_admin.UpdateMemoryLayerRequest(), {}, ], ) -def test_create_app_profile(request_type, transport: str = "grpc"): +def test_update_memory_layer(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5058,31 +5058,23 @@ def test_create_app_profile(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_app_profile), "__call__" + type(client.transport.update_memory_layer), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.AppProfile( - name="name_value", - etag="etag_value", - description="description_value", - priority=instance.AppProfile.Priority.PRIORITY_LOW, - ) - response = client.create_app_profile(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.CreateAppProfileRequest() + request = bigtable_instance_admin.UpdateMemoryLayerRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.AppProfile) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.description == "description_value" + assert isinstance(response, future.Future) -def test_create_app_profile_non_empty_request_with_auto_populated_field(): +def test_update_memory_layer_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -5093,29 +5085,23 @@ def test_create_app_profile_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.CreateAppProfileRequest( - parent="parent_value", - app_profile_id="app_profile_id_value", - ) + request = bigtable_instance_admin.UpdateMemoryLayerRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_app_profile), "__call__" + type(client.transport.update_memory_layer), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_app_profile(request=request) + client.update_memory_layer(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateAppProfileRequest( - parent="parent_value", - app_profile_id="app_profile_id_value", - ) + request_msg = bigtable_instance_admin.UpdateMemoryLayerRequest() assert args[0] == request_msg -def test_create_app_profile_use_cached_wrapped_rpc(): +def test_update_memory_layer_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5130,7 +5116,7 @@ def test_create_app_profile_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_app_profile in client._transport._wrapped_methods + client._transport.update_memory_layer in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5138,16 +5124,21 @@ def test_create_app_profile_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_app_profile] = ( + client._transport._wrapped_methods[client._transport.update_memory_layer] = ( mock_rpc ) request = {} - client.create_app_profile(request) + client.update_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_app_profile(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_memory_layer(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5155,7 +5146,7 @@ def test_create_app_profile_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_app_profile_async_use_cached_wrapped_rpc( +async def test_update_memory_layer_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5172,7 +5163,7 @@ async def test_create_app_profile_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_app_profile + client._client._transport.update_memory_layer in client._client._transport._wrapped_methods ) @@ -5180,16 +5171,21 @@ async def test_create_app_profile_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_app_profile + client._client._transport.update_memory_layer ] = mock_rpc request = {} - await client.create_app_profile(request) + await client.update_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.create_app_profile(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_memory_layer(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5200,11 +5196,11 @@ async def test_create_app_profile_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateAppProfileRequest(), + bigtable_instance_admin.UpdateMemoryLayerRequest(), {}, ], ) -async def test_create_app_profile_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_memory_layer_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5216,48 +5212,41 @@ async def test_create_app_profile_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_app_profile), "__call__" + type(client.transport.update_memory_layer), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.AppProfile( - name="name_value", - etag="etag_value", - description="description_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.create_app_profile(request) + response = await client.update_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.CreateAppProfileRequest() + request = bigtable_instance_admin.UpdateMemoryLayerRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.AppProfile) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.description == "description_value" + assert isinstance(response, future.Future) -def test_create_app_profile_field_headers(): +def test_update_memory_layer_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.CreateAppProfileRequest() + request = bigtable_instance_admin.UpdateMemoryLayerRequest() - request.parent = "parent_value" + request.memory_layer.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_app_profile), "__call__" + type(client.transport.update_memory_layer), "__call__" ) as call: - call.return_value = instance.AppProfile() - client.create_app_profile(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5268,28 +5257,30 @@ def test_create_app_profile_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "memory_layer.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_app_profile_field_headers_async(): +async def test_update_memory_layer_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.CreateAppProfileRequest() + request = bigtable_instance_admin.UpdateMemoryLayerRequest() - request.parent = "parent_value" + request.memory_layer.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_app_profile), "__call__" + type(client.transport.update_memory_layer), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) - await client.create_app_profile(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5300,45 +5291,41 @@ async def test_create_app_profile_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "memory_layer.name=name_value", ) in kw["metadata"] -def test_create_app_profile_flattened(): +def test_update_memory_layer_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_app_profile), "__call__" + type(client.transport.update_memory_layer), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.AppProfile() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_app_profile( - parent="parent_value", - app_profile_id="app_profile_id_value", - app_profile=instance.AppProfile(name="name_value"), + client.update_memory_layer( + memory_layer=instance.MemoryLayer(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].app_profile_id - mock_val = "app_profile_id_value" + arg = args[0].memory_layer + mock_val = instance.MemoryLayer(name="name_value") assert arg == mock_val - arg = args[0].app_profile - mock_val = instance.AppProfile(name="name_value") + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_create_app_profile_flattened_error(): +def test_update_memory_layer_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5346,53 +5333,50 @@ def test_create_app_profile_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_app_profile( - bigtable_instance_admin.CreateAppProfileRequest(), - parent="parent_value", - app_profile_id="app_profile_id_value", - app_profile=instance.AppProfile(name="name_value"), + client.update_memory_layer( + bigtable_instance_admin.UpdateMemoryLayerRequest(), + memory_layer=instance.MemoryLayer(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_create_app_profile_flattened_async(): +async def test_update_memory_layer_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_app_profile), "__call__" + type(client.transport.update_memory_layer), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.AppProfile() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_app_profile( - parent="parent_value", - app_profile_id="app_profile_id_value", - app_profile=instance.AppProfile(name="name_value"), + response = await client.update_memory_layer( + memory_layer=instance.MemoryLayer(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].app_profile_id - mock_val = "app_profile_id_value" + arg = args[0].memory_layer + mock_val = instance.MemoryLayer(name="name_value") assert arg == mock_val - arg = args[0].app_profile - mock_val = instance.AppProfile(name="name_value") + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_create_app_profile_flattened_error_async(): +async def test_update_memory_layer_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5400,22 +5384,21 @@ async def test_create_app_profile_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_app_profile( - bigtable_instance_admin.CreateAppProfileRequest(), - parent="parent_value", - app_profile_id="app_profile_id_value", - app_profile=instance.AppProfile(name="name_value"), + await client.update_memory_layer( + bigtable_instance_admin.UpdateMemoryLayerRequest(), + memory_layer=instance.MemoryLayer(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetAppProfileRequest(), + bigtable_instance_admin.ListMemoryLayersRequest(), {}, ], ) -def test_get_app_profile(request_type, transport: str = "grpc"): +def test_list_memory_layers(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5426,30 +5409,29 @@ def test_get_app_profile(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.AppProfile( - name="name_value", - etag="etag_value", - description="description_value", - priority=instance.AppProfile.Priority.PRIORITY_LOW, + call.return_value = bigtable_instance_admin.ListMemoryLayersResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", ) - response = client.get_app_profile(request) + response = client.list_memory_layers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.GetAppProfileRequest() + request = bigtable_instance_admin.ListMemoryLayersRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.AppProfile) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.description == "description_value" + assert isinstance(response, pagers.ListMemoryLayersPager) + assert response.failed_locations == ["failed_locations_value"] + assert response.next_page_token == "next_page_token_value" -def test_get_app_profile_non_empty_request_with_auto_populated_field(): +def test_list_memory_layers_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -5460,25 +5442,29 @@ def test_get_app_profile_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.GetAppProfileRequest( - name="name_value", + request = bigtable_instance_admin.ListMemoryLayersRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_app_profile(request=request) + client.list_memory_layers(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetAppProfileRequest( - name="name_value", + request_msg = bigtable_instance_admin.ListMemoryLayersRequest( + parent="parent_value", + page_token="page_token_value", ) assert args[0] == request_msg -def test_get_app_profile_use_cached_wrapped_rpc(): +def test_list_memory_layers_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5492,21 +5478,25 @@ def test_get_app_profile_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_app_profile in client._transport._wrapped_methods + assert ( + client._transport.list_memory_layers in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_app_profile] = mock_rpc + client._transport._wrapped_methods[client._transport.list_memory_layers] = ( + mock_rpc + ) request = {} - client.get_app_profile(request) + client.list_memory_layers(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_app_profile(request) + client.list_memory_layers(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5514,7 +5504,7 @@ def test_get_app_profile_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_app_profile_async_use_cached_wrapped_rpc( +async def test_list_memory_layers_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5531,7 +5521,7 @@ async def test_get_app_profile_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_app_profile + client._client._transport.list_memory_layers in client._client._transport._wrapped_methods ) @@ -5539,16 +5529,16 @@ async def test_get_app_profile_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_app_profile + client._client._transport.list_memory_layers ] = mock_rpc request = {} - await client.get_app_profile(request) + await client.list_memory_layers(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_app_profile(request) + await client.list_memory_layers(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5559,11 +5549,11 @@ async def test_get_app_profile_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetAppProfileRequest(), + bigtable_instance_admin.ListMemoryLayersRequest(), {}, ], ) -async def test_get_app_profile_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_memory_layers_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5574,45 +5564,47 @@ async def test_get_app_profile_async(request_type, transport: str = "grpc_asynci request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.AppProfile( - name="name_value", - etag="etag_value", - description="description_value", + bigtable_instance_admin.ListMemoryLayersResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", ) ) - response = await client.get_app_profile(request) + response = await client.list_memory_layers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.GetAppProfileRequest() + request = bigtable_instance_admin.ListMemoryLayersRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.AppProfile) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.description == "description_value" + assert isinstance(response, pagers.ListMemoryLayersAsyncPager) + assert response.failed_locations == ["failed_locations_value"] + assert response.next_page_token == "next_page_token_value" -def test_get_app_profile_field_headers(): +def test_list_memory_layers_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.GetAppProfileRequest() + request = bigtable_instance_admin.ListMemoryLayersRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: - call.return_value = instance.AppProfile() - client.get_app_profile(request) + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListMemoryLayersResponse() + client.list_memory_layers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5623,26 +5615,30 @@ def test_get_app_profile_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_app_profile_field_headers_async(): +async def test_list_memory_layers_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.GetAppProfileRequest() + request = bigtable_instance_admin.ListMemoryLayersRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) - await client.get_app_profile(request) + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListMemoryLayersResponse() + ) + await client.list_memory_layers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5653,35 +5649,37 @@ async def test_get_app_profile_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_app_profile_flattened(): +def test_list_memory_layers_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.AppProfile() + call.return_value = bigtable_instance_admin.ListMemoryLayersResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_app_profile( - name="name_value", + client.list_memory_layers( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_app_profile_flattened_error(): +def test_list_memory_layers_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5689,41 +5687,45 @@ def test_get_app_profile_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_app_profile( - bigtable_instance_admin.GetAppProfileRequest(), - name="name_value", + client.list_memory_layers( + bigtable_instance_admin.ListMemoryLayersRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_app_profile_flattened_async(): +async def test_list_memory_layers_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.AppProfile() + call.return_value = bigtable_instance_admin.ListMemoryLayersResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListMemoryLayersResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_app_profile( - name="name_value", + response = await client.list_memory_layers( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_app_profile_flattened_error_async(): +async def test_list_memory_layers_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5731,20 +5733,223 @@ async def test_get_app_profile_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_app_profile( - bigtable_instance_admin.GetAppProfileRequest(), - name="name_value", + await client.list_memory_layers( + bigtable_instance_admin.ListMemoryLayersRequest(), + parent="parent_value", + ) + + +def test_list_memory_layers_pager(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_memory_layers(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.MemoryLayer) for i in results) + + +def test_list_memory_layers_pages(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + ), + RuntimeError, + ) + pages = list(client.list_memory_layers(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_memory_layers_async_pager(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memory_layers), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_memory_layers( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instance.MemoryLayer) for i in responses) + + +@pytest.mark.asyncio +async def test_list_memory_layers_async_pages(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memory_layers), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_memory_layers(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListAppProfilesRequest(), + bigtable_instance_admin.GetMemoryLayerRequest(), {}, ], ) -def test_list_app_profiles(request_type, transport: str = "grpc"): +def test_get_memory_layer(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5755,29 +5960,29 @@ def test_list_app_profiles(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListAppProfilesResponse( - next_page_token="next_page_token_value", - failed_locations=["failed_locations_value"], + call.return_value = instance.MemoryLayer( + name="name_value", + etag="etag_value", + state=instance.MemoryLayer.State.READY, ) - response = client.list_app_profiles(request) + response = client.get_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListAppProfilesRequest() + request = bigtable_instance_admin.GetMemoryLayerRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAppProfilesPager) - assert response.next_page_token == "next_page_token_value" - assert response.failed_locations == ["failed_locations_value"] + assert isinstance(response, instance.MemoryLayer) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.state == instance.MemoryLayer.State.READY -def test_list_app_profiles_non_empty_request_with_auto_populated_field(): +def test_get_memory_layer_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -5788,29 +5993,25 @@ def test_list_app_profiles_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.ListAppProfilesRequest( - parent="parent_value", - page_token="page_token_value", + request = bigtable_instance_admin.GetMemoryLayerRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_app_profiles(request=request) + client.get_memory_layer(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListAppProfilesRequest( - parent="parent_value", - page_token="page_token_value", + request_msg = bigtable_instance_admin.GetMemoryLayerRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_app_profiles_use_cached_wrapped_rpc(): +def test_get_memory_layer_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5824,23 +6025,23 @@ def test_list_app_profiles_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_app_profiles in client._transport._wrapped_methods + assert client._transport.get_memory_layer in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_app_profiles] = ( + client._transport._wrapped_methods[client._transport.get_memory_layer] = ( mock_rpc ) request = {} - client.list_app_profiles(request) + client.get_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_app_profiles(request) + client.get_memory_layer(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5848,7 +6049,7 @@ def test_list_app_profiles_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_app_profiles_async_use_cached_wrapped_rpc( +async def test_get_memory_layer_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5865,7 +6066,7 @@ async def test_list_app_profiles_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_app_profiles + client._client._transport.get_memory_layer in client._client._transport._wrapped_methods ) @@ -5873,16 +6074,16 @@ async def test_list_app_profiles_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_app_profiles + client._client._transport.get_memory_layer ] = mock_rpc request = {} - await client.list_app_profiles(request) + await client.get_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_app_profiles(request) + await client.get_memory_layer(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5893,11 +6094,11 @@ async def test_list_app_profiles_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListAppProfilesRequest(), + bigtable_instance_admin.GetMemoryLayerRequest(), {}, ], ) -async def test_list_app_profiles_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_memory_layer_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5908,47 +6109,45 @@ async def test_list_app_profiles_async(request_type, transport: str = "grpc_asyn request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListAppProfilesResponse( - next_page_token="next_page_token_value", - failed_locations=["failed_locations_value"], + instance.MemoryLayer( + name="name_value", + etag="etag_value", + state=instance.MemoryLayer.State.READY, ) ) - response = await client.list_app_profiles(request) + response = await client.get_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListAppProfilesRequest() + request = bigtable_instance_admin.GetMemoryLayerRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAppProfilesAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.failed_locations == ["failed_locations_value"] + assert isinstance(response, instance.MemoryLayer) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.state == instance.MemoryLayer.State.READY -def test_list_app_profiles_field_headers(): +def test_get_memory_layer_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListAppProfilesRequest() + request = bigtable_instance_admin.GetMemoryLayerRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: - call.return_value = bigtable_instance_admin.ListAppProfilesResponse() - client.list_app_profiles(request) + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: + call.return_value = instance.MemoryLayer() + client.get_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5959,30 +6158,28 @@ def test_list_app_profiles_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_app_profiles_field_headers_async(): +async def test_get_memory_layer_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListAppProfilesRequest() + request = bigtable_instance_admin.GetMemoryLayerRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListAppProfilesResponse() + instance.MemoryLayer() ) - await client.list_app_profiles(request) + await client.get_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5993,37 +6190,35 @@ async def test_list_app_profiles_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_app_profiles_flattened(): +def test_get_memory_layer_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListAppProfilesResponse() + call.return_value = instance.MemoryLayer() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_app_profiles( - parent="parent_value", + client.get_memory_layer( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_app_profiles_flattened_error(): +def test_get_memory_layer_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6031,45 +6226,43 @@ def test_list_app_profiles_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_app_profiles( - bigtable_instance_admin.ListAppProfilesRequest(), - parent="parent_value", + client.get_memory_layer( + bigtable_instance_admin.GetMemoryLayerRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_app_profiles_flattened_async(): +async def test_get_memory_layer_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListAppProfilesResponse() + call.return_value = instance.MemoryLayer() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListAppProfilesResponse() + instance.MemoryLayer() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_app_profiles( - parent="parent_value", + response = await client.get_memory_layer( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_app_profiles_flattened_error_async(): +async def test_get_memory_layer_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6077,223 +6270,20 @@ async def test_list_app_profiles_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_app_profiles( - bigtable_instance_admin.ListAppProfilesRequest(), - parent="parent_value", + await client.get_memory_layer( + bigtable_instance_admin.GetMemoryLayerRequest(), + name="name_value", ) -def test_list_app_profiles_pager(transport_name: str = "grpc"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - instance.AppProfile(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[], - next_page_token="def", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_app_profiles(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, instance.AppProfile) for i in results) - - -def test_list_app_profiles_pages(transport_name: str = "grpc"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - instance.AppProfile(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[], - next_page_token="def", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - ], - ), - RuntimeError, - ) - pages = list(client.list_app_profiles(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_app_profiles_async_pager(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - instance.AppProfile(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[], - next_page_token="def", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_app_profiles( - request={}, - ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, instance.AppProfile) for i in responses) - - -@pytest.mark.asyncio -async def test_list_app_profiles_async_pages(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_app_profiles), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - instance.AppProfile(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[], - next_page_token="def", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListAppProfilesResponse( - app_profiles=[ - instance.AppProfile(), - instance.AppProfile(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_app_profiles(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.UpdateAppProfileRequest(), + bigtable_instance_admin.CreateAppProfileRequest(), {}, ], ) -def test_update_app_profile(request_type, transport: str = "grpc"): +def test_create_app_profile(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6305,23 +6295,31 @@ def test_update_app_profile(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_app_profile), "__call__" + type(client.transport.create_app_profile), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_app_profile(request) + call.return_value = instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + priority=instance.AppProfile.Priority.PRIORITY_LOW, + ) + response = client.create_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.UpdateAppProfileRequest() + request = bigtable_instance_admin.CreateAppProfileRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, instance.AppProfile) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.description == "description_value" -def test_update_app_profile_non_empty_request_with_auto_populated_field(): +def test_create_app_profile_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -6332,23 +6330,29 @@ def test_update_app_profile_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.UpdateAppProfileRequest() + request = bigtable_instance_admin.CreateAppProfileRequest( + parent="parent_value", + app_profile_id="app_profile_id_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_app_profile), "__call__" + type(client.transport.create_app_profile), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_app_profile(request=request) + client.create_app_profile(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.UpdateAppProfileRequest() + request_msg = bigtable_instance_admin.CreateAppProfileRequest( + parent="parent_value", + app_profile_id="app_profile_id_value", + ) assert args[0] == request_msg -def test_update_app_profile_use_cached_wrapped_rpc(): +def test_create_app_profile_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6363,7 +6367,7 @@ def test_update_app_profile_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_app_profile in client._transport._wrapped_methods + client._transport.create_app_profile in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6371,21 +6375,16 @@ def test_update_app_profile_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_app_profile] = ( + client._transport._wrapped_methods[client._transport.create_app_profile] = ( mock_rpc ) request = {} - client.update_app_profile(request) + client.create_app_profile(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_app_profile(request) + client.create_app_profile(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6393,7 +6392,7 @@ def test_update_app_profile_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_app_profile_async_use_cached_wrapped_rpc( +async def test_create_app_profile_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6410,7 +6409,7 @@ async def test_update_app_profile_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_app_profile + client._client._transport.create_app_profile in client._client._transport._wrapped_methods ) @@ -6418,21 +6417,16 @@ async def test_update_app_profile_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_app_profile + client._client._transport.create_app_profile ] = mock_rpc request = {} - await client.update_app_profile(request) + await client.create_app_profile(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_app_profile(request) + await client.create_app_profile(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6443,11 +6437,11 @@ async def test_update_app_profile_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.UpdateAppProfileRequest(), + bigtable_instance_admin.CreateAppProfileRequest(), {}, ], ) -async def test_update_app_profile_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_app_profile_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6459,41 +6453,48 @@ async def test_update_app_profile_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_app_profile), "__call__" + type(client.transport.create_app_profile), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + ) ) - response = await client.update_app_profile(request) + response = await client.create_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.UpdateAppProfileRequest() + request = bigtable_instance_admin.CreateAppProfileRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, instance.AppProfile) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.description == "description_value" -def test_update_app_profile_field_headers(): +def test_create_app_profile_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.UpdateAppProfileRequest() + request = bigtable_instance_admin.CreateAppProfileRequest() - request.app_profile.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_app_profile), "__call__" + type(client.transport.create_app_profile), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_app_profile(request) + call.return_value = instance.AppProfile() + client.create_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6504,30 +6505,28 @@ def test_update_app_profile_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "app_profile.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_app_profile_field_headers_async(): +async def test_create_app_profile_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.UpdateAppProfileRequest() + request = bigtable_instance_admin.CreateAppProfileRequest() - request.app_profile.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_app_profile), "__call__" + type(client.transport.create_app_profile), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.update_app_profile(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) + await client.create_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6538,41 +6537,45 @@ async def test_update_app_profile_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "app_profile.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_app_profile_flattened(): +def test_create_app_profile_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_app_profile), "__call__" + type(client.transport.create_app_profile), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = instance.AppProfile() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_app_profile( + client.create_app_profile( + parent="parent_value", + app_profile_id="app_profile_id_value", app_profile=instance.AppProfile(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].app_profile_id + mock_val = "app_profile_id_value" + assert arg == mock_val arg = args[0].app_profile mock_val = instance.AppProfile(name="name_value") assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val -def test_update_app_profile_flattened_error(): +def test_create_app_profile_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6580,50 +6583,53 @@ def test_update_app_profile_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_app_profile( - bigtable_instance_admin.UpdateAppProfileRequest(), + client.create_app_profile( + bigtable_instance_admin.CreateAppProfileRequest(), + parent="parent_value", + app_profile_id="app_profile_id_value", app_profile=instance.AppProfile(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_app_profile_flattened_async(): +async def test_create_app_profile_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_app_profile), "__call__" + type(client.transport.create_app_profile), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = instance.AppProfile() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_app_profile( + response = await client.create_app_profile( + parent="parent_value", + app_profile_id="app_profile_id_value", app_profile=instance.AppProfile(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].app_profile_id + mock_val = "app_profile_id_value" + assert arg == mock_val arg = args[0].app_profile mock_val = instance.AppProfile(name="name_value") assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val @pytest.mark.asyncio -async def test_update_app_profile_flattened_error_async(): +async def test_create_app_profile_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6631,21 +6637,22 @@ async def test_update_app_profile_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_app_profile( - bigtable_instance_admin.UpdateAppProfileRequest(), + await client.create_app_profile( + bigtable_instance_admin.CreateAppProfileRequest(), + parent="parent_value", + app_profile_id="app_profile_id_value", app_profile=instance.AppProfile(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteAppProfileRequest(), + bigtable_instance_admin.GetAppProfileRequest(), {}, ], ) -def test_delete_app_profile(request_type, transport: str = "grpc"): +def test_get_app_profile(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6656,24 +6663,30 @@ def test_delete_app_profile(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_app_profile(request) + call.return_value = instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + priority=instance.AppProfile.Priority.PRIORITY_LOW, + ) + response = client.get_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.DeleteAppProfileRequest() + request = bigtable_instance_admin.GetAppProfileRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, instance.AppProfile) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.description == "description_value" -def test_delete_app_profile_non_empty_request_with_auto_populated_field(): +def test_get_app_profile_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -6684,27 +6697,25 @@ def test_delete_app_profile_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.DeleteAppProfileRequest( + request = bigtable_instance_admin.GetAppProfileRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_app_profile(request=request) + client.get_app_profile(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteAppProfileRequest( + request_msg = bigtable_instance_admin.GetAppProfileRequest( name="name_value", ) assert args[0] == request_msg -def test_delete_app_profile_use_cached_wrapped_rpc(): +def test_get_app_profile_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6718,25 +6729,21 @@ def test_delete_app_profile_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_app_profile in client._transport._wrapped_methods - ) + assert client._transport.get_app_profile in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_app_profile] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_app_profile] = mock_rpc request = {} - client.delete_app_profile(request) + client.get_app_profile(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_app_profile(request) + client.get_app_profile(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6744,7 +6751,7 @@ def test_delete_app_profile_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_app_profile_async_use_cached_wrapped_rpc( +async def test_get_app_profile_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6761,7 +6768,7 @@ async def test_delete_app_profile_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_app_profile + client._client._transport.get_app_profile in client._client._transport._wrapped_methods ) @@ -6769,16 +6776,16 @@ async def test_delete_app_profile_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_app_profile + client._client._transport.get_app_profile ] = mock_rpc request = {} - await client.delete_app_profile(request) + await client.get_app_profile(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.delete_app_profile(request) + await client.get_app_profile(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6789,11 +6796,11 @@ async def test_delete_app_profile_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteAppProfileRequest(), + bigtable_instance_admin.GetAppProfileRequest(), {}, ], ) -async def test_delete_app_profile_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_app_profile_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6804,40 +6811,45 @@ async def test_delete_app_profile_async(request_type, transport: str = "grpc_asy request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_app_profile(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.AppProfile( + name="name_value", + etag="etag_value", + description="description_value", + ) + ) + response = await client.get_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.DeleteAppProfileRequest() + request = bigtable_instance_admin.GetAppProfileRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, instance.AppProfile) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.description == "description_value" -def test_delete_app_profile_field_headers(): +def test_get_app_profile_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.DeleteAppProfileRequest() + request = bigtable_instance_admin.GetAppProfileRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: - call.return_value = None - client.delete_app_profile(request) + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + call.return_value = instance.AppProfile() + client.get_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6853,23 +6865,21 @@ def test_delete_app_profile_field_headers(): @pytest.mark.asyncio -async def test_delete_app_profile_field_headers_async(): +async def test_get_app_profile_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.DeleteAppProfileRequest() + request = bigtable_instance_admin.GetAppProfileRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_app_profile(request) + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) + await client.get_app_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6884,22 +6894,19 @@ async def test_delete_app_profile_field_headers_async(): ) in kw["metadata"] -def test_delete_app_profile_flattened(): +def test_get_app_profile_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = instance.AppProfile() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_app_profile( + client.get_app_profile( name="name_value", - ignore_warnings=True, ) # Establish that the underlying call was made with the expected @@ -6909,12 +6916,9 @@ def test_delete_app_profile_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].ignore_warnings - mock_val = True - assert arg == mock_val -def test_delete_app_profile_flattened_error(): +def test_get_app_profile_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6922,32 +6926,28 @@ def test_delete_app_profile_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_app_profile( - bigtable_instance_admin.DeleteAppProfileRequest(), + client.get_app_profile( + bigtable_instance_admin.GetAppProfileRequest(), name="name_value", - ignore_warnings=True, ) @pytest.mark.asyncio -async def test_delete_app_profile_flattened_async(): +async def test_get_app_profile_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_app_profile), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_app_profile), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = instance.AppProfile() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.AppProfile()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_app_profile( + response = await client.get_app_profile( name="name_value", - ignore_warnings=True, ) # Establish that the underlying call was made with the expected @@ -6957,13 +6957,10 @@ async def test_delete_app_profile_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].ignore_warnings - mock_val = True - assert arg == mock_val @pytest.mark.asyncio -async def test_delete_app_profile_flattened_error_async(): +async def test_get_app_profile_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6971,21 +6968,20 @@ async def test_delete_app_profile_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_app_profile( - bigtable_instance_admin.DeleteAppProfileRequest(), + await client.get_app_profile( + bigtable_instance_admin.GetAppProfileRequest(), name="name_value", - ignore_warnings=True, ) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.GetIamPolicyRequest(), + bigtable_instance_admin.ListAppProfilesRequest(), {}, ], ) -def test_get_iam_policy(request_type, transport: str = "grpc"): +def test_list_app_profiles(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6996,27 +6992,29 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + call.return_value = bigtable_instance_admin.ListAppProfilesResponse( + next_page_token="next_page_token_value", + failed_locations=["failed_locations_value"], ) - response = client.get_iam_policy(request) + response = client.list_app_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.GetIamPolicyRequest() + request = bigtable_instance_admin.ListAppProfilesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, pagers.ListAppProfilesPager) + assert response.next_page_token == "next_page_token_value" + assert response.failed_locations == ["failed_locations_value"] -def test_get_iam_policy_non_empty_request_with_auto_populated_field(): +def test_list_app_profiles_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -7027,25 +7025,29 @@ def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", + request = bigtable_instance_admin.ListAppProfilesRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_iam_policy(request=request) + client.list_app_profiles(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", + request_msg = bigtable_instance_admin.ListAppProfilesRequest( + parent="parent_value", + page_token="page_token_value", ) assert args[0] == request_msg -def test_get_iam_policy_use_cached_wrapped_rpc(): +def test_list_app_profiles_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7059,21 +7061,23 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods + assert client._transport.list_app_profiles in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + client._transport._wrapped_methods[client._transport.list_app_profiles] = ( + mock_rpc + ) request = {} - client.get_iam_policy(request) + client.list_app_profiles(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_iam_policy(request) + client.list_app_profiles(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7081,7 +7085,7 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_iam_policy_async_use_cached_wrapped_rpc( +async def test_list_app_profiles_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7098,7 +7102,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_iam_policy + client._client._transport.list_app_profiles in client._client._transport._wrapped_methods ) @@ -7106,16 +7110,16 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_iam_policy + client._client._transport.list_app_profiles ] = mock_rpc request = {} - await client.get_iam_policy(request) + await client.list_app_profiles(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_iam_policy(request) + await client.list_app_profiles(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7126,11 +7130,11 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.GetIamPolicyRequest(), + bigtable_instance_admin.ListAppProfilesRequest(), {}, ], ) -async def test_get_iam_policy_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_app_profiles_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7141,43 +7145,47 @@ async def test_get_iam_policy_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", + bigtable_instance_admin.ListAppProfilesResponse( + next_page_token="next_page_token_value", + failed_locations=["failed_locations_value"], ) ) - response = await client.get_iam_policy(request) + response = await client.list_app_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.GetIamPolicyRequest() + request = bigtable_instance_admin.ListAppProfilesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, pagers.ListAppProfilesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.failed_locations == ["failed_locations_value"] -def test_get_iam_policy_field_headers(): +def test_list_app_profiles_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() + request = bigtable_instance_admin.ListAppProfilesRequest() - request.resource = "resource_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request) + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListAppProfilesResponse() + client.list_app_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7188,26 +7196,30 @@ def test_get_iam_policy_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "resource=resource_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): +async def test_list_app_profiles_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() + request = bigtable_instance_admin.ListAppProfilesRequest() - request.resource = "resource_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.get_iam_policy(request) + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListAppProfilesResponse() + ) + await client.list_app_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7218,52 +7230,37 @@ async def test_get_iam_policy_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "resource=resource_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_iam_policy_from_dict_foreign(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_get_iam_policy_flattened(): +def test_list_app_profiles_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() + call.return_value = bigtable_instance_admin.ListAppProfilesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_iam_policy( - resource="resource_value", + client.list_app_profiles( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = "resource_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_iam_policy_flattened_error(): +def test_list_app_profiles_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7271,41 +7268,45 @@ def test_get_iam_policy_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource="resource_value", + client.list_app_profiles( + bigtable_instance_admin.ListAppProfilesRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): +async def test_list_app_profiles_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() + call.return_value = bigtable_instance_admin.ListAppProfilesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListAppProfilesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource="resource_value", + response = await client.list_app_profiles( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = "resource_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): +async def test_list_app_profiles_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7313,80 +7314,1660 @@ async def test_get_iam_policy_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource="resource_value", + await client.list_app_profiles( + bigtable_instance_admin.ListAppProfilesRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest(), - {}, - ], -) -def test_set_iam_policy(request_type, transport: str = "grpc"): +def test_list_app_profiles_pager(transport_name: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - -def test_set_iam_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + instance.AppProfile(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[], + next_page_token="def", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_app_profiles(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.AppProfile) for i in results) + + +def test_list_app_profiles_pages(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_profiles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + instance.AppProfile(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[], + next_page_token="def", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + ], + ), + RuntimeError, + ) + pages = list(client.list_app_profiles(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_app_profiles_async_pager(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_profiles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + instance.AppProfile(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[], + next_page_token="def", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_app_profiles( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instance.AppProfile) for i in responses) + + +@pytest.mark.asyncio +async def test_list_app_profiles_async_pages(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_profiles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + instance.AppProfile(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[], + next_page_token="def", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListAppProfilesResponse( + app_profiles=[ + instance.AppProfile(), + instance.AppProfile(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_app_profiles(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.UpdateAppProfileRequest(), + {}, + ], +) +def test_update_app_profile(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.UpdateAppProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_app_profile_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.UpdateAppProfileRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_app_profile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateAppProfileRequest() + assert args[0] == request_msg + + +def test_update_app_profile_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_app_profile in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_app_profile] = ( + mock_rpc + ) + request = {} + client.update_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_app_profile(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_app_profile_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_app_profile + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_app_profile + ] = mock_rpc + + request = {} + await client.update_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_app_profile(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.UpdateAppProfileRequest(), + {}, + ], +) +async def test_update_app_profile_async(request_type, transport: str = "grpc_asyncio"): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.UpdateAppProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_app_profile_field_headers(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.UpdateAppProfileRequest() + + request.app_profile.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app_profile.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_app_profile_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.UpdateAppProfileRequest() + + request.app_profile.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app_profile.name=name_value", + ) in kw["metadata"] + + +def test_update_app_profile_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_app_profile( + app_profile=instance.AppProfile(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].app_profile + mock_val = instance.AppProfile(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_app_profile_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_app_profile( + bigtable_instance_admin.UpdateAppProfileRequest(), + app_profile=instance.AppProfile(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_app_profile_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_app_profile( + app_profile=instance.AppProfile(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].app_profile + mock_val = instance.AppProfile(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_app_profile_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_app_profile( + bigtable_instance_admin.UpdateAppProfileRequest(), + app_profile=instance.AppProfile(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.DeleteAppProfileRequest(), + {}, + ], +) +def test_delete_app_profile(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.DeleteAppProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_app_profile_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = bigtable_instance_admin.DeleteAppProfileRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_app_profile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.DeleteAppProfileRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_app_profile_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_app_profile in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_app_profile] = ( + mock_rpc + ) + request = {} + client.delete_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_app_profile(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_app_profile_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_app_profile + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_app_profile + ] = mock_rpc + + request = {} + await client.delete_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_app_profile(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.DeleteAppProfileRequest(), + {}, + ], +) +async def test_delete_app_profile_async(request_type, transport: str = "grpc_asyncio"): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bigtable_instance_admin.DeleteAppProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_app_profile_field_headers(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.DeleteAppProfileRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + call.return_value = None + client.delete_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_app_profile_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = bigtable_instance_admin.DeleteAppProfileRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_app_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_app_profile_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_app_profile( + name="name_value", + ignore_warnings=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ignore_warnings + mock_val = True + assert arg == mock_val + + +def test_delete_app_profile_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_app_profile( + bigtable_instance_admin.DeleteAppProfileRequest(), + name="name_value", + ignore_warnings=True, + ) + + +@pytest.mark.asyncio +async def test_delete_app_profile_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_app_profile( + name="name_value", + ignore_warnings=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ignore_warnings + mock_val = True + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_app_profile_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_app_profile( + bigtable_instance_admin.DeleteAppProfileRequest(), + name="name_value", + ignore_warnings=True, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest(), + {}, + ], +) +def test_get_iam_policy(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + assert args[0] == request_msg + + +def test_get_iam_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_iam_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_iam_policy + ] = mock_rpc + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest(), + {}, + ], +) +async def test_get_iam_policy_async(request_type, transport: str = "grpc_asyncio"): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource_value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict_foreign(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest(), + {}, + ], +) +def test_set_iam_policy(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + assert args[0] == request_msg + + +def test_set_iam_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.set_iam_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.set_iam_policy + ] = mock_rpc + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest(), + {}, + ], +) +async def test_set_iam_policy_async(request_type, transport: str = "grpc_asyncio"): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource_value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict_foreign(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest(), + {}, + ], +) +def test_test_iam_permissions(request_type, transport: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource="resource_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.set_iam_policy(request=request) + client.test_iam_permissions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest( + request_msg = iam_policy_pb2.TestIamPermissionsRequest( resource="resource_value", ) assert args[0] == request_msg -def test_set_iam_policy_use_cached_wrapped_rpc(): +def test_test_iam_permissions_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7400,21 +8981,25 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods + assert ( + client._transport.test_iam_permissions in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + client._transport._wrapped_methods[client._transport.test_iam_permissions] = ( + mock_rpc + ) request = {} - client.set_iam_policy(request) + client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_iam_policy(request) + client.test_iam_permissions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7422,7 +9007,7 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_set_iam_policy_async_use_cached_wrapped_rpc( +async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7439,7 +9024,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.set_iam_policy + client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods ) @@ -7447,16 +9032,16 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.set_iam_policy + client._client._transport.test_iam_permissions ] = mock_rpc request = {} - await client.set_iam_policy(request) + await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.set_iam_policy(request) + await client.test_iam_permissions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7467,11 +9052,13 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.SetIamPolicyRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), {}, ], ) -async def test_set_iam_policy_async(request_type, transport: str = "grpc_asyncio"): +async def test_test_iam_permissions_async( + request_type, transport: str = "grpc_asyncio" +): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7482,43 +9069,45 @@ async def test_set_iam_policy_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], ) ) - response = await client.set_iam_policy(request) + response = await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] -def test_set_iam_policy_field_headers(): +def test_test_iam_permissions_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() request.resource = "resource_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request) + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7534,21 +9123,25 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): +async def test_test_iam_permissions_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() request.resource = "resource_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.set_iam_policy(request) + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7563,37 +9156,41 @@ async def test_set_iam_policy_field_headers_async(): ) in kw["metadata"] -def test_set_iam_policy_from_dict_foreign(): +def test_test_iam_permissions_from_dict_foreign(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.set_iam_policy( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions( request={ "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]), + "permissions": ["permissions_value"], } ) call.assert_called() -def test_set_iam_policy_flattened(): +def test_test_iam_permissions_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.set_iam_policy( + client.test_iam_permissions( resource="resource_value", + permissions=["permissions_value"], ) # Establish that the underlying call was made with the expected @@ -7603,9 +9200,12 @@ def test_set_iam_policy_flattened(): arg = args[0].resource mock_val = "resource_value" assert arg == mock_val + arg = args[0].permissions + mock_val = ["permissions_value"] + assert arg == mock_val -def test_set_iam_policy_flattened_error(): +def test_test_iam_permissions_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7613,28 +9213,34 @@ def test_set_iam_policy_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", + permissions=["permissions_value"], ) @pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): +async def test_test_iam_permissions_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.set_iam_policy( + response = await client.test_iam_permissions( resource="resource_value", + permissions=["permissions_value"], ) # Establish that the underlying call was made with the expected @@ -7644,10 +9250,13 @@ async def test_set_iam_policy_flattened_async(): arg = args[0].resource mock_val = "resource_value" assert arg == mock_val + arg = args[0].permissions + mock_val = ["permissions_value"] + assert arg == mock_val @pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): +async def test_test_iam_permissions_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7655,20 +9264,21 @@ async def test_set_iam_policy_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", + permissions=["permissions_value"], ) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.TestIamPermissionsRequest(), + bigtable_instance_admin.ListHotTabletsRequest(), {}, ], ) -def test_test_iam_permissions(request_type, transport: str = "grpc"): +def test_list_hot_tablets(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7679,27 +9289,25 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], + call.return_value = bigtable_instance_admin.ListHotTabletsResponse( + next_page_token="next_page_token_value", ) - response = client.test_iam_permissions(request) + response = client.list_hot_tablets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.TestIamPermissionsRequest() + request = bigtable_instance_admin.ListHotTabletsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] + assert isinstance(response, pagers.ListHotTabletsPager) + assert response.next_page_token == "next_page_token_value" -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): +def test_list_hot_tablets_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -7710,27 +9318,27 @@ def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", + request = bigtable_instance_admin.ListHotTabletsRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.test_iam_permissions(request=request) + client.list_hot_tablets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", + request_msg = bigtable_instance_admin.ListHotTabletsRequest( + parent="parent_value", + page_token="page_token_value", ) assert args[0] == request_msg -def test_test_iam_permissions_use_cached_wrapped_rpc(): +def test_list_hot_tablets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7744,25 +9352,23 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.test_iam_permissions in client._transport._wrapped_methods - ) + assert client._transport.list_hot_tablets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.test_iam_permissions] = ( + client._transport._wrapped_methods[client._transport.list_hot_tablets] = ( mock_rpc ) request = {} - client.test_iam_permissions(request) + client.list_hot_tablets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.test_iam_permissions(request) + client.list_hot_tablets(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7770,7 +9376,7 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc( +async def test_list_hot_tablets_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7787,7 +9393,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.test_iam_permissions + client._client._transport.list_hot_tablets in client._client._transport._wrapped_methods ) @@ -7795,16 +9401,16 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.test_iam_permissions + client._client._transport.list_hot_tablets ] = mock_rpc request = {} - await client.test_iam_permissions(request) + await client.list_hot_tablets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.test_iam_permissions(request) + await client.list_hot_tablets(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7815,13 +9421,11 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.TestIamPermissionsRequest(), + bigtable_instance_admin.ListHotTabletsRequest(), {}, ], ) -async def test_test_iam_permissions_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_list_hot_tablets_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7832,45 +9436,41 @@ async def test_test_iam_permissions_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], + bigtable_instance_admin.ListHotTabletsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.test_iam_permissions(request) + response = await client.list_hot_tablets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.TestIamPermissionsRequest() + request = bigtable_instance_admin.ListHotTabletsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] + assert isinstance(response, pagers.ListHotTabletsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_test_iam_permissions_field_headers(): +def test_list_hot_tablets_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() + request = bigtable_instance_admin.ListHotTabletsRequest() - request.resource = "resource_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request) + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + call.return_value = bigtable_instance_admin.ListHotTabletsResponse() + client.list_hot_tablets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7881,30 +9481,28 @@ def test_test_iam_permissions_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "resource=resource_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): +async def test_list_hot_tablets_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() + request = bigtable_instance_admin.ListHotTabletsRequest() - request.resource = "resource_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() + bigtable_instance_admin.ListHotTabletsResponse() ) - await client.test_iam_permissions(request) + await client.list_hot_tablets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7915,133 +9513,295 @@ async def test_test_iam_permissions_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "resource=resource_value", + "parent=parent_value", ) in kw["metadata"] -def test_test_iam_permissions_from_dict_foreign(): +def test_list_hot_tablets_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) + # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } + call.return_value = bigtable_instance_admin.ListHotTabletsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_hot_tablets( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_hot_tablets_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hot_tablets( + bigtable_instance_admin.ListHotTabletsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_hot_tablets_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListHotTabletsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListHotTabletsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_hot_tablets( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_hot_tablets_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_hot_tablets( + bigtable_instance_admin.ListHotTabletsRequest(), + parent="parent_value", + ) + + +def test_list_hot_tablets_pager(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + instance.HotTablet(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[], + next_page_token="def", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - call.assert_called() - + pager = client.list_hot_tablets(request={}, retry=retry, timeout=timeout) -def test_test_iam_permissions_flattened(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource="resource_value", - permissions=["permissions_value"], - ) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = "resource_value" - assert arg == mock_val - arg = args[0].permissions - mock_val = ["permissions_value"] - assert arg == mock_val + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.HotTablet) for i in results) -def test_test_iam_permissions_flattened_error(): +def test_list_hot_tablets_pages(transport_name: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + instance.HotTablet(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[], + next_page_token="def", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + ], + ), + RuntimeError, ) + pages = list(client.list_hot_tablets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): +async def test_list_hot_tablets_async_pager(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" + type(client.transport.list_hot_tablets), "__call__", new_callable=mock.AsyncMock ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + instance.HotTablet(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[], + next_page_token="def", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + ], + ), + RuntimeError, ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource="resource_value", - permissions=["permissions_value"], + async_pager = await client.list_hot_tablets( + request={}, ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = "resource_value" - assert arg == mock_val - arg = args[0].permissions - mock_val = ["permissions_value"] - assert arg == mock_val + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instance.HotTablet) for i in responses) @pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): +async def test_list_hot_tablets_async_pages(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hot_tablets), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + instance.HotTablet(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[], + next_page_token="def", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListHotTabletsResponse( + hot_tablets=[ + instance.HotTablet(), + instance.HotTablet(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_hot_tablets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListHotTabletsRequest(), + bigtable_instance_admin.CreateLogicalViewRequest(), {}, ], ) -def test_list_hot_tablets(request_type, transport: str = "grpc"): +def test_create_logical_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8052,25 +9812,24 @@ def test_list_hot_tablets(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListHotTabletsResponse( - next_page_token="next_page_token_value", - ) - response = client.list_hot_tablets(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListHotTabletsRequest() + request = bigtable_instance_admin.CreateLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListHotTabletsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_hot_tablets_non_empty_request_with_auto_populated_field(): +def test_create_logical_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -8081,27 +9840,29 @@ def test_list_hot_tablets_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.ListHotTabletsRequest( + request = bigtable_instance_admin.CreateLogicalViewRequest( parent="parent_value", - page_token="page_token_value", + logical_view_id="logical_view_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_hot_tablets(request=request) + client.create_logical_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListHotTabletsRequest( + request_msg = bigtable_instance_admin.CreateLogicalViewRequest( parent="parent_value", - page_token="page_token_value", + logical_view_id="logical_view_id_value", ) assert args[0] == request_msg -def test_list_hot_tablets_use_cached_wrapped_rpc(): +def test_create_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8115,23 +9876,30 @@ def test_list_hot_tablets_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_hot_tablets in client._transport._wrapped_methods + assert ( + client._transport.create_logical_view in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_hot_tablets] = ( + client._transport._wrapped_methods[client._transport.create_logical_view] = ( mock_rpc ) request = {} - client.list_hot_tablets(request) + client.create_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_hot_tablets(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8139,7 +9907,7 @@ def test_list_hot_tablets_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_hot_tablets_async_use_cached_wrapped_rpc( +async def test_create_logical_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8156,7 +9924,7 @@ async def test_list_hot_tablets_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_hot_tablets + client._client._transport.create_logical_view in client._client._transport._wrapped_methods ) @@ -8164,16 +9932,21 @@ async def test_list_hot_tablets_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_hot_tablets + client._client._transport.create_logical_view ] = mock_rpc request = {} - await client.list_hot_tablets(request) + await client.create_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_hot_tablets(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8184,11 +9957,11 @@ async def test_list_hot_tablets_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListHotTabletsRequest(), + bigtable_instance_admin.CreateLogicalViewRequest(), {}, ], ) -async def test_list_hot_tablets_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_logical_view_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8199,41 +9972,42 @@ async def test_list_hot_tablets_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListHotTabletsResponse( - next_page_token="next_page_token_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_hot_tablets(request) + response = await client.create_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListHotTabletsRequest() + request = bigtable_instance_admin.CreateLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListHotTabletsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_hot_tablets_field_headers(): +def test_create_logical_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListHotTabletsRequest() + request = bigtable_instance_admin.CreateLogicalViewRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: - call.return_value = bigtable_instance_admin.ListHotTabletsResponse() - client.list_hot_tablets(request) + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8249,23 +10023,25 @@ def test_list_hot_tablets_field_headers(): @pytest.mark.asyncio -async def test_list_hot_tablets_field_headers_async(): +async def test_create_logical_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListHotTabletsRequest() + request = bigtable_instance_admin.CreateLogicalViewRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListHotTabletsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_hot_tablets(request) + await client.create_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8280,19 +10056,23 @@ async def test_list_hot_tablets_field_headers_async(): ) in kw["metadata"] -def test_list_hot_tablets_flattened(): +def test_create_logical_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: + with mock.patch.object( + type(client.transport.create_logical_view), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListHotTabletsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_hot_tablets( + client.create_logical_view( parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", ) # Establish that the underlying call was made with the expected @@ -8302,269 +10082,94 @@ def test_list_hot_tablets_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - - -def test_list_hot_tablets_flattened_error(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_hot_tablets( - bigtable_instance_admin.ListHotTabletsRequest(), - parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_hot_tablets_flattened_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListHotTabletsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListHotTabletsResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_hot_tablets( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") + assert arg == mock_val + arg = args[0].logical_view_id + mock_val = "logical_view_id_value" assert arg == mock_val -@pytest.mark.asyncio -async def test_list_hot_tablets_flattened_error_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_hot_tablets( - bigtable_instance_admin.ListHotTabletsRequest(), - parent="parent_value", - ) - - -def test_list_hot_tablets_pager(transport_name: str = "grpc"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - instance.HotTablet(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[], - next_page_token="def", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_hot_tablets(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, instance.HotTablet) for i in results) - - -def test_list_hot_tablets_pages(transport_name: str = "grpc"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_hot_tablets), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - instance.HotTablet(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[], - next_page_token="def", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - ], - ), - RuntimeError, - ) - pages = list(client.list_hot_tablets(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_hot_tablets_async_pager(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_hot_tablets), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - instance.HotTablet(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[], - next_page_token="def", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_hot_tablets( - request={}, - ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) +def test_create_logical_view_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - assert len(responses) == 6 - assert all(isinstance(i, instance.HotTablet) for i in responses) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_logical_view( + bigtable_instance_admin.CreateLogicalViewRequest(), + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", + ) @pytest.mark.asyncio -async def test_list_hot_tablets_async_pages(): +async def test_create_logical_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_hot_tablets), "__call__", new_callable=mock.AsyncMock + type(client.transport.create_logical_view), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - instance.HotTablet(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[], - next_page_token="def", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListHotTabletsResponse( - hot_tablets=[ - instance.HotTablet(), - instance.HotTablet(), - ], - ), - RuntimeError, + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_logical_view( + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") + assert arg == mock_val + arg = args[0].logical_view_id + mock_val = "logical_view_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_logical_view_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_logical_view( + bigtable_instance_admin.CreateLogicalViewRequest(), + parent="parent_value", + logical_view=instance.LogicalView(name="name_value"), + logical_view_id="logical_view_id_value", ) - pages = [] - async for page_ in (await client.list_hot_tablets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateLogicalViewRequest(), + bigtable_instance_admin.GetLogicalViewRequest(), {}, ], ) -def test_create_logical_view(request_type, transport: str = "grpc"): +def test_get_logical_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8575,24 +10180,31 @@ def test_create_logical_view(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_logical_view), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_logical_view(request) + call.return_value = instance.LogicalView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) + response = client.get_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.CreateLogicalViewRequest() + request = bigtable_instance_admin.GetLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, instance.LogicalView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + assert response.deletion_protection is True -def test_create_logical_view_non_empty_request_with_auto_populated_field(): +def test_get_logical_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -8603,29 +10215,25 @@ def test_create_logical_view_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.CreateLogicalViewRequest( - parent="parent_value", - logical_view_id="logical_view_id_value", + request = bigtable_instance_admin.GetLogicalViewRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_logical_view), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_logical_view(request=request) + client.get_logical_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateLogicalViewRequest( - parent="parent_value", - logical_view_id="logical_view_id_value", + request_msg = bigtable_instance_admin.GetLogicalViewRequest( + name="name_value", ) assert args[0] == request_msg -def test_create_logical_view_use_cached_wrapped_rpc(): +def test_get_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8639,30 +10247,23 @@ def test_create_logical_view_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_logical_view in client._transport._wrapped_methods - ) + assert client._transport.get_logical_view in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_logical_view] = ( + client._transport._wrapped_methods[client._transport.get_logical_view] = ( mock_rpc ) request = {} - client.create_logical_view(request) + client.get_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_logical_view(request) + client.get_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8670,7 +10271,7 @@ def test_create_logical_view_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_logical_view_async_use_cached_wrapped_rpc( +async def test_get_logical_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8687,7 +10288,7 @@ async def test_create_logical_view_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_logical_view + client._client._transport.get_logical_view in client._client._transport._wrapped_methods ) @@ -8695,21 +10296,16 @@ async def test_create_logical_view_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_logical_view + client._client._transport.get_logical_view ] = mock_rpc request = {} - await client.create_logical_view(request) + await client.get_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_logical_view(request) + await client.get_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8720,11 +10316,11 @@ async def test_create_logical_view_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateLogicalViewRequest(), + bigtable_instance_admin.GetLogicalViewRequest(), {}, ], ) -async def test_create_logical_view_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_logical_view_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8735,42 +10331,47 @@ async def test_create_logical_view_async(request_type, transport: str = "grpc_as request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_logical_view), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + instance.LogicalView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) ) - response = await client.create_logical_view(request) + response = await client.get_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.CreateLogicalViewRequest() + request = bigtable_instance_admin.GetLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, instance.LogicalView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + assert response.deletion_protection is True -def test_create_logical_view_field_headers(): +def test_get_logical_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.CreateLogicalViewRequest() + request = bigtable_instance_admin.GetLogicalViewRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_logical_view), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_logical_view(request) + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + call.return_value = instance.LogicalView() + client.get_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8781,30 +10382,28 @@ def test_create_logical_view_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_logical_view_field_headers_async(): +async def test_get_logical_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.CreateLogicalViewRequest() + request = bigtable_instance_admin.GetLogicalViewRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_logical_view), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + instance.LogicalView() ) - await client.create_logical_view(request) + await client.get_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8815,45 +10414,35 @@ async def test_create_logical_view_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_logical_view_flattened(): +def test_get_logical_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_logical_view), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = instance.LogicalView() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_logical_view( - parent="parent_value", - logical_view=instance.LogicalView(name="name_value"), - logical_view_id="logical_view_id_value", + client.get_logical_view( + name="name_value", ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].logical_view - mock_val = instance.LogicalView(name="name_value") - assert arg == mock_val - arg = args[0].logical_view_id - mock_val = "logical_view_id_value" + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_logical_view_flattened_error(): +def test_get_logical_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8861,55 +10450,43 @@ def test_create_logical_view_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_logical_view( - bigtable_instance_admin.CreateLogicalViewRequest(), - parent="parent_value", - logical_view=instance.LogicalView(name="name_value"), - logical_view_id="logical_view_id_value", + client.get_logical_view( + bigtable_instance_admin.GetLogicalViewRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_logical_view_flattened_async(): +async def test_get_logical_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_logical_view), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = instance.LogicalView() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + instance.LogicalView() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_logical_view( - parent="parent_value", - logical_view=instance.LogicalView(name="name_value"), - logical_view_id="logical_view_id_value", + response = await client.get_logical_view( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].logical_view - mock_val = instance.LogicalView(name="name_value") - assert arg == mock_val - arg = args[0].logical_view_id - mock_val = "logical_view_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_logical_view_flattened_error_async(): +async def test_get_logical_view_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8917,22 +10494,20 @@ async def test_create_logical_view_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_logical_view( - bigtable_instance_admin.CreateLogicalViewRequest(), - parent="parent_value", - logical_view=instance.LogicalView(name="name_value"), - logical_view_id="logical_view_id_value", + await client.get_logical_view( + bigtable_instance_admin.GetLogicalViewRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetLogicalViewRequest(), + bigtable_instance_admin.ListLogicalViewsRequest(), {}, ], ) -def test_get_logical_view(request_type, transport: str = "grpc"): +def test_list_logical_views(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8943,31 +10518,27 @@ def test_get_logical_view(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.LogicalView( - name="name_value", - query="query_value", - etag="etag_value", - deletion_protection=True, + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse( + next_page_token="next_page_token_value", ) - response = client.get_logical_view(request) + response = client.list_logical_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.GetLogicalViewRequest() + request = bigtable_instance_admin.ListLogicalViewsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.LogicalView) - assert response.name == "name_value" - assert response.query == "query_value" - assert response.etag == "etag_value" - assert response.deletion_protection is True + assert isinstance(response, pagers.ListLogicalViewsPager) + assert response.next_page_token == "next_page_token_value" -def test_get_logical_view_non_empty_request_with_auto_populated_field(): +def test_list_logical_views_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -8978,25 +10549,29 @@ def test_get_logical_view_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.GetLogicalViewRequest( - name="name_value", + request = bigtable_instance_admin.ListLogicalViewsRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_logical_view(request=request) + client.list_logical_views(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetLogicalViewRequest( - name="name_value", + request_msg = bigtable_instance_admin.ListLogicalViewsRequest( + parent="parent_value", + page_token="page_token_value", ) assert args[0] == request_msg -def test_get_logical_view_use_cached_wrapped_rpc(): +def test_list_logical_views_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9010,23 +10585,25 @@ def test_get_logical_view_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_logical_view in client._transport._wrapped_methods + assert ( + client._transport.list_logical_views in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_logical_view] = ( + client._transport._wrapped_methods[client._transport.list_logical_views] = ( mock_rpc ) request = {} - client.get_logical_view(request) + client.list_logical_views(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_logical_view(request) + client.list_logical_views(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9034,7 +10611,7 @@ def test_get_logical_view_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_logical_view_async_use_cached_wrapped_rpc( +async def test_list_logical_views_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9051,7 +10628,7 @@ async def test_get_logical_view_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_logical_view + client._client._transport.list_logical_views in client._client._transport._wrapped_methods ) @@ -9059,16 +10636,16 @@ async def test_get_logical_view_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_logical_view + client._client._transport.list_logical_views ] = mock_rpc request = {} - await client.get_logical_view(request) + await client.list_logical_views(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_logical_view(request) + await client.list_logical_views(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9079,11 +10656,11 @@ async def test_get_logical_view_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetLogicalViewRequest(), + bigtable_instance_admin.ListLogicalViewsRequest(), {}, ], ) -async def test_get_logical_view_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_logical_views_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9094,47 +10671,45 @@ async def test_get_logical_view_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.LogicalView( - name="name_value", - query="query_value", - etag="etag_value", - deletion_protection=True, + bigtable_instance_admin.ListLogicalViewsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.get_logical_view(request) + response = await client.list_logical_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.GetLogicalViewRequest() + request = bigtable_instance_admin.ListLogicalViewsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.LogicalView) - assert response.name == "name_value" - assert response.query == "query_value" - assert response.etag == "etag_value" - assert response.deletion_protection is True + assert isinstance(response, pagers.ListLogicalViewsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_get_logical_view_field_headers(): +def test_list_logical_views_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.GetLogicalViewRequest() + request = bigtable_instance_admin.ListLogicalViewsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: - call.return_value = instance.LogicalView() - client.get_logical_view(request) + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + client.list_logical_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9145,132 +10720,341 @@ def test_get_logical_view_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_logical_view_field_headers_async(): +async def test_list_logical_views_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.GetLogicalViewRequest() + request = bigtable_instance_admin.ListLogicalViewsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.LogicalView() + bigtable_instance_admin.ListLogicalViewsResponse() ) - await client.get_logical_view(request) + await client.list_logical_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_logical_views_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_logical_views( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_logical_views_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_logical_views( + bigtable_instance_admin.ListLogicalViewsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_logical_views_flattened_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListLogicalViewsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_logical_views( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_logical_views_flattened_error_async(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_logical_views( + bigtable_instance_admin.ListLogicalViewsRequest(), + parent="parent_value", + ) -def test_get_logical_view_flattened(): +def test_list_logical_views_pager(transport_name: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = instance.LogicalView() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_logical_view( - name="name_value", + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, ) - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_logical_views(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") -def test_get_logical_view_flattened_error(): + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.LogicalView) for i in results) + + +def test_list_logical_views_pages(transport_name: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_logical_view( - bigtable_instance_admin.GetLogicalViewRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, ) + pages = list(client.list_logical_views(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_get_logical_view_flattened_async(): +async def test_list_logical_views_async_pager(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_logical_view), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = instance.LogicalView() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.LogicalView() + with mock.patch.object( + type(client.transport.list_logical_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_logical_view( - name="name_value", + async_pager = await client.list_logical_views( + request={}, ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instance.LogicalView) for i in responses) @pytest.mark.asyncio -async def test_get_logical_view_flattened_error_async(): +async def test_list_logical_views_async_pages(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_logical_view( - bigtable_instance_admin.GetLogicalViewRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_logical_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + instance.LogicalView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListLogicalViewsResponse( + logical_views=[ + instance.LogicalView(), + instance.LogicalView(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_logical_views(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListLogicalViewsRequest(), + bigtable_instance_admin.UpdateLogicalViewRequest(), {}, ], ) -def test_list_logical_views(request_type, transport: str = "grpc"): +def test_update_logical_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9282,26 +11066,23 @@ def test_list_logical_views(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_logical_views), "__call__" + type(client.transport.update_logical_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListLogicalViewsResponse( - next_page_token="next_page_token_value", - ) - response = client.list_logical_views(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListLogicalViewsRequest() + request = bigtable_instance_admin.UpdateLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogicalViewsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_logical_views_non_empty_request_with_auto_populated_field(): +def test_update_logical_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -9312,29 +11093,23 @@ def test_list_logical_views_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.ListLogicalViewsRequest( - parent="parent_value", - page_token="page_token_value", - ) + request = bigtable_instance_admin.UpdateLogicalViewRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_logical_views), "__call__" + type(client.transport.update_logical_view), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_logical_views(request=request) + client.update_logical_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListLogicalViewsRequest( - parent="parent_value", - page_token="page_token_value", - ) + request_msg = bigtable_instance_admin.UpdateLogicalViewRequest() assert args[0] == request_msg -def test_list_logical_views_use_cached_wrapped_rpc(): +def test_update_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9349,7 +11124,7 @@ def test_list_logical_views_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_logical_views in client._transport._wrapped_methods + client._transport.update_logical_view in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -9357,16 +11132,21 @@ def test_list_logical_views_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_logical_views] = ( + client._transport._wrapped_methods[client._transport.update_logical_view] = ( mock_rpc ) request = {} - client.list_logical_views(request) + client.update_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_logical_views(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9374,7 +11154,7 @@ def test_list_logical_views_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_logical_views_async_use_cached_wrapped_rpc( +async def test_update_logical_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9391,7 +11171,7 @@ async def test_list_logical_views_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_logical_views + client._client._transport.update_logical_view in client._client._transport._wrapped_methods ) @@ -9399,16 +11179,21 @@ async def test_list_logical_views_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_logical_views + client._client._transport.update_logical_view ] = mock_rpc request = {} - await client.list_logical_views(request) + await client.update_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_logical_views(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9419,11 +11204,11 @@ async def test_list_logical_views_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListLogicalViewsRequest(), + bigtable_instance_admin.UpdateLogicalViewRequest(), {}, ], ) -async def test_list_logical_views_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_logical_view_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9435,44 +11220,41 @@ async def test_list_logical_views_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_logical_views), "__call__" + type(client.transport.update_logical_view), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListLogicalViewsResponse( - next_page_token="next_page_token_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_logical_views(request) + response = await client.update_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListLogicalViewsRequest() + request = bigtable_instance_admin.UpdateLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogicalViewsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_logical_views_field_headers(): +def test_update_logical_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListLogicalViewsRequest() + request = bigtable_instance_admin.UpdateLogicalViewRequest() - request.parent = "parent_value" + request.logical_view.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_logical_views), "__call__" + type(client.transport.update_logical_view), "__call__" ) as call: - call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() - client.list_logical_views(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9483,30 +11265,30 @@ def test_list_logical_views_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "logical_view.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_logical_views_field_headers_async(): +async def test_update_logical_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListLogicalViewsRequest() + request = bigtable_instance_admin.UpdateLogicalViewRequest() - request.parent = "parent_value" + request.logical_view.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_logical_views), "__call__" + type(client.transport.update_logical_view), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListLogicalViewsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_logical_views(request) + await client.update_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9517,307 +11299,114 @@ async def test_list_logical_views_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "logical_view.name=name_value", ) in kw["metadata"] -def test_list_logical_views_flattened(): +def test_update_logical_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_logical_views), "__call__" + type(client.transport.update_logical_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_logical_views( - parent="parent_value", + client.update_logical_view( + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") assert arg == mock_val - - -def test_list_logical_views_flattened_error(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_logical_views( - bigtable_instance_admin.ListLogicalViewsRequest(), - parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_logical_views_flattened_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logical_views), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListLogicalViewsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListLogicalViewsResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_logical_views( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -@pytest.mark.asyncio -async def test_list_logical_views_flattened_error_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_logical_views( - bigtable_instance_admin.ListLogicalViewsRequest(), - parent="parent_value", - ) - - -def test_list_logical_views_pager(transport_name: str = "grpc"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logical_views), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - instance.LogicalView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_logical_views(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, instance.LogicalView) for i in results) - - -def test_list_logical_views_pages(transport_name: str = "grpc"): +def test_update_logical_view_flattened_error(): client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logical_views), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - instance.LogicalView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - ], - ), - RuntimeError, + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_logical_view( + bigtable_instance_admin.UpdateLogicalViewRequest(), + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - pages = list(client.list_logical_views(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_logical_views_async_pager(): +async def test_update_logical_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_logical_views), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.update_logical_view), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - instance.LogicalView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - ], - ), - RuntimeError, + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - async_pager = await client.list_logical_views( - request={}, + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_logical_view( + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - assert len(responses) == 6 - assert all(isinstance(i, instance.LogicalView) for i in responses) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].logical_view + mock_val = instance.LogicalView(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val @pytest.mark.asyncio -async def test_list_logical_views_async_pages(): +async def test_update_logical_view_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logical_views), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - instance.LogicalView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListLogicalViewsResponse( - logical_views=[ - instance.LogicalView(), - instance.LogicalView(), - ], - ), - RuntimeError, + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_logical_view( + bigtable_instance_admin.UpdateLogicalViewRequest(), + logical_view=instance.LogicalView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - pages = [] - async for page_ in (await client.list_logical_views(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.UpdateLogicalViewRequest(), + bigtable_instance_admin.DeleteLogicalViewRequest(), {}, ], ) -def test_update_logical_view(request_type, transport: str = "grpc"): +def test_delete_logical_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9829,23 +11418,23 @@ def test_update_logical_view(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_logical_view), "__call__" + type(client.transport.delete_logical_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_logical_view(request) + call.return_value = None + response = client.delete_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.UpdateLogicalViewRequest() + request = bigtable_instance_admin.DeleteLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert response is None -def test_update_logical_view_non_empty_request_with_auto_populated_field(): +def test_delete_logical_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -9856,23 +11445,29 @@ def test_update_logical_view_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.UpdateLogicalViewRequest() + request = bigtable_instance_admin.DeleteLogicalViewRequest( + name="name_value", + etag="etag_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_logical_view), "__call__" + type(client.transport.delete_logical_view), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_logical_view(request=request) + client.delete_logical_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.UpdateLogicalViewRequest() + request_msg = bigtable_instance_admin.DeleteLogicalViewRequest( + name="name_value", + etag="etag_value", + ) assert args[0] == request_msg -def test_update_logical_view_use_cached_wrapped_rpc(): +def test_delete_logical_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9887,7 +11482,7 @@ def test_update_logical_view_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_logical_view in client._transport._wrapped_methods + client._transport.delete_logical_view in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -9895,21 +11490,16 @@ def test_update_logical_view_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_logical_view] = ( + client._transport._wrapped_methods[client._transport.delete_logical_view] = ( mock_rpc ) request = {} - client.update_logical_view(request) + client.delete_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_logical_view(request) + client.delete_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9917,7 +11507,7 @@ def test_update_logical_view_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_logical_view_async_use_cached_wrapped_rpc( +async def test_delete_logical_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9934,7 +11524,7 @@ async def test_update_logical_view_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_logical_view + client._client._transport.delete_logical_view in client._client._transport._wrapped_methods ) @@ -9942,21 +11532,16 @@ async def test_update_logical_view_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_logical_view + client._client._transport.delete_logical_view ] = mock_rpc request = {} - await client.update_logical_view(request) + await client.delete_logical_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_logical_view(request) + await client.delete_logical_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9967,11 +11552,11 @@ async def test_update_logical_view_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.UpdateLogicalViewRequest(), + bigtable_instance_admin.DeleteLogicalViewRequest(), {}, ], ) -async def test_update_logical_view_async(request_type, transport: str = "grpc_asyncio"): +async def test_delete_logical_view_async(request_type, transport: str = "grpc_asyncio"): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9983,41 +11568,39 @@ async def test_update_logical_view_async(request_type, transport: str = "grpc_as # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_logical_view), "__call__" + type(client.transport.delete_logical_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_logical_view(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.UpdateLogicalViewRequest() + request = bigtable_instance_admin.DeleteLogicalViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert response is None -def test_update_logical_view_field_headers(): +def test_delete_logical_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.UpdateLogicalViewRequest() + request = bigtable_instance_admin.DeleteLogicalViewRequest() - request.logical_view.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_logical_view), "__call__" + type(client.transport.delete_logical_view), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_logical_view(request) + call.return_value = None + client.delete_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10028,30 +11611,28 @@ def test_update_logical_view_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "logical_view.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_logical_view_field_headers_async(): +async def test_delete_logical_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.UpdateLogicalViewRequest() + request = bigtable_instance_admin.DeleteLogicalViewRequest() - request.logical_view.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_logical_view), "__call__" + type(client.transport.delete_logical_view), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.update_logical_view(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_logical_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10062,41 +11643,37 @@ async def test_update_logical_view_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "logical_view.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_logical_view_flattened(): +def test_delete_logical_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_logical_view), "__call__" + type(client.transport.delete_logical_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_logical_view( - logical_view=instance.LogicalView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_logical_view( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].logical_view - mock_val = instance.LogicalView(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_logical_view_flattened_error(): +def test_delete_logical_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10104,50 +11681,43 @@ def test_update_logical_view_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_logical_view( - bigtable_instance_admin.UpdateLogicalViewRequest(), - logical_view=instance.LogicalView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_logical_view( + bigtable_instance_admin.DeleteLogicalViewRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_logical_view_flattened_async(): +async def test_delete_logical_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_logical_view), "__call__" + type(client.transport.delete_logical_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_logical_view( - logical_view=instance.LogicalView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.delete_logical_view( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].logical_view - mock_val = instance.LogicalView(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_logical_view_flattened_error_async(): +async def test_delete_logical_view_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10155,21 +11725,20 @@ async def test_update_logical_view_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_logical_view( - bigtable_instance_admin.UpdateLogicalViewRequest(), - logical_view=instance.LogicalView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.delete_logical_view( + bigtable_instance_admin.DeleteLogicalViewRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteLogicalViewRequest(), + bigtable_instance_admin.CreateMaterializedViewRequest(), {}, ], ) -def test_delete_logical_view(request_type, transport: str = "grpc"): +def test_create_materialized_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10181,23 +11750,23 @@ def test_delete_logical_view(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_logical_view), "__call__" + type(client.transport.create_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_logical_view(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.DeleteLogicalViewRequest() + request = bigtable_instance_admin.CreateMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, future.Future) -def test_delete_logical_view_non_empty_request_with_auto_populated_field(): +def test_create_materialized_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -10208,29 +11777,29 @@ def test_delete_logical_view_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.DeleteLogicalViewRequest( - name="name_value", - etag="etag_value", + request = bigtable_instance_admin.CreateMaterializedViewRequest( + parent="parent_value", + materialized_view_id="materialized_view_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_logical_view), "__call__" + type(client.transport.create_materialized_view), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_logical_view(request=request) + client.create_materialized_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteLogicalViewRequest( - name="name_value", - etag="etag_value", + request_msg = bigtable_instance_admin.CreateMaterializedViewRequest( + parent="parent_value", + materialized_view_id="materialized_view_id_value", ) assert args[0] == request_msg -def test_delete_logical_view_use_cached_wrapped_rpc(): +def test_create_materialized_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10245,7 +11814,8 @@ def test_delete_logical_view_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_logical_view in client._transport._wrapped_methods + client._transport.create_materialized_view + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -10253,16 +11823,21 @@ def test_delete_logical_view_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_logical_view] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_materialized_view + ] = mock_rpc request = {} - client.delete_logical_view(request) + client.create_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_logical_view(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10270,7 +11845,7 @@ def test_delete_logical_view_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_logical_view_async_use_cached_wrapped_rpc( +async def test_create_materialized_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10287,7 +11862,7 @@ async def test_delete_logical_view_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_logical_view + client._client._transport.create_materialized_view in client._client._transport._wrapped_methods ) @@ -10295,16 +11870,21 @@ async def test_delete_logical_view_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_logical_view + client._client._transport.create_materialized_view ] = mock_rpc request = {} - await client.delete_logical_view(request) + await client.create_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.delete_logical_view(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10315,11 +11895,13 @@ async def test_delete_logical_view_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteLogicalViewRequest(), + bigtable_instance_admin.CreateMaterializedViewRequest(), {}, ], ) -async def test_delete_logical_view_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_materialized_view_async( + request_type, transport: str = "grpc_asyncio" +): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10331,39 +11913,41 @@ async def test_delete_logical_view_async(request_type, transport: str = "grpc_as # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_logical_view), "__call__" + type(client.transport.create_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_logical_view(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.DeleteLogicalViewRequest() + request = bigtable_instance_admin.CreateMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, future.Future) -def test_delete_logical_view_field_headers(): +def test_create_materialized_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.DeleteLogicalViewRequest() + request = bigtable_instance_admin.CreateMaterializedViewRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_logical_view), "__call__" + type(client.transport.create_materialized_view), "__call__" ) as call: - call.return_value = None - client.delete_logical_view(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10374,28 +11958,30 @@ def test_delete_logical_view_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_logical_view_field_headers_async(): +async def test_create_materialized_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.DeleteLogicalViewRequest() + request = bigtable_instance_admin.CreateMaterializedViewRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_logical_view), "__call__" + type(client.transport.create_materialized_view), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_logical_view(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10406,37 +11992,45 @@ async def test_delete_logical_view_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_logical_view_flattened(): +def test_create_materialized_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_logical_view), "__call__" + type(client.transport.create_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_logical_view( - name="name_value", + client.create_materialized_view( + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].materialized_view_id + mock_val = "materialized_view_id_value" assert arg == mock_val -def test_delete_logical_view_flattened_error(): +def test_create_materialized_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10444,43 +12038,55 @@ def test_delete_logical_view_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_logical_view( - bigtable_instance_admin.DeleteLogicalViewRequest(), - name="name_value", + client.create_materialized_view( + bigtable_instance_admin.CreateMaterializedViewRequest(), + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", ) @pytest.mark.asyncio -async def test_delete_logical_view_flattened_async(): +async def test_create_materialized_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_logical_view), "__call__" + type(client.transport.create_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_logical_view( - name="name_value", + response = await client.create_materialized_view( + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].materialized_view_id + mock_val = "materialized_view_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_logical_view_flattened_error_async(): +async def test_create_materialized_view_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10488,20 +12094,22 @@ async def test_delete_logical_view_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_logical_view( - bigtable_instance_admin.DeleteLogicalViewRequest(), - name="name_value", + await client.create_materialized_view( + bigtable_instance_admin.CreateMaterializedViewRequest(), + parent="parent_value", + materialized_view=instance.MaterializedView(name="name_value"), + materialized_view_id="materialized_view_id_value", ) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateMaterializedViewRequest(), + bigtable_instance_admin.GetMaterializedViewRequest(), {}, ], ) -def test_create_materialized_view(request_type, transport: str = "grpc"): +def test_get_materialized_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10513,23 +12121,32 @@ def test_create_materialized_view(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.get_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_materialized_view(request) + call.return_value = instance.MaterializedView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) + response = client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.CreateMaterializedViewRequest() + request = bigtable_instance_admin.GetMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, instance.MaterializedView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + assert response.deletion_protection is True -def test_create_materialized_view_non_empty_request_with_auto_populated_field(): +def test_get_materialized_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -10540,29 +12157,27 @@ def test_create_materialized_view_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.CreateMaterializedViewRequest( - parent="parent_value", - materialized_view_id="materialized_view_id_value", + request = bigtable_instance_admin.GetMaterializedViewRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.get_materialized_view), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_materialized_view(request=request) + client.get_materialized_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateMaterializedViewRequest( - parent="parent_value", - materialized_view_id="materialized_view_id_value", + request_msg = bigtable_instance_admin.GetMaterializedViewRequest( + name="name_value", ) assert args[0] == request_msg -def test_create_materialized_view_use_cached_wrapped_rpc(): +def test_get_materialized_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10577,7 +12192,7 @@ def test_create_materialized_view_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_materialized_view + client._transport.get_materialized_view in client._transport._wrapped_methods ) @@ -10586,21 +12201,16 @@ def test_create_materialized_view_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_materialized_view - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_materialized_view] = ( + mock_rpc + ) request = {} - client.create_materialized_view(request) + client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_materialized_view(request) + client.get_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10608,7 +12218,7 @@ def test_create_materialized_view_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_materialized_view_async_use_cached_wrapped_rpc( +async def test_get_materialized_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10625,7 +12235,7 @@ async def test_create_materialized_view_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_materialized_view + client._client._transport.get_materialized_view in client._client._transport._wrapped_methods ) @@ -10633,21 +12243,16 @@ async def test_create_materialized_view_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_materialized_view + client._client._transport.get_materialized_view ] = mock_rpc request = {} - await client.create_materialized_view(request) + await client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_materialized_view(request) + await client.get_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10658,11 +12263,11 @@ async def test_create_materialized_view_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateMaterializedViewRequest(), + bigtable_instance_admin.GetMaterializedViewRequest(), {}, ], ) -async def test_create_materialized_view_async( +async def test_get_materialized_view_async( request_type, transport: str = "grpc_asyncio" ): client = BigtableInstanceAdminAsyncClient( @@ -10676,41 +12281,50 @@ async def test_create_materialized_view_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.get_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + instance.MaterializedView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) ) - response = await client.create_materialized_view(request) + response = await client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.CreateMaterializedViewRequest() + request = bigtable_instance_admin.GetMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, instance.MaterializedView) + assert response.name == "name_value" + assert response.query == "query_value" + assert response.etag == "etag_value" + assert response.deletion_protection is True -def test_create_materialized_view_field_headers(): +def test_get_materialized_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.CreateMaterializedViewRequest() + request = bigtable_instance_admin.GetMaterializedViewRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.get_materialized_view), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_materialized_view(request) + call.return_value = instance.MaterializedView() + client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10721,30 +12335,30 @@ def test_create_materialized_view_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_materialized_view_field_headers_async(): +async def test_get_materialized_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.CreateMaterializedViewRequest() + request = bigtable_instance_admin.GetMaterializedViewRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.get_materialized_view), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + instance.MaterializedView() ) - await client.create_materialized_view(request) + await client.get_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10755,45 +12369,37 @@ async def test_create_materialized_view_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_materialized_view_flattened(): +def test_get_materialized_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.get_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = instance.MaterializedView() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_materialized_view( - parent="parent_value", - materialized_view=instance.MaterializedView(name="name_value"), - materialized_view_id="materialized_view_id_value", + client.get_materialized_view( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].materialized_view - mock_val = instance.MaterializedView(name="name_value") - assert arg == mock_val - arg = args[0].materialized_view_id - mock_val = "materialized_view_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_materialized_view_flattened_error(): +def test_get_materialized_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10801,55 +12407,45 @@ def test_create_materialized_view_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_materialized_view( - bigtable_instance_admin.CreateMaterializedViewRequest(), - parent="parent_value", - materialized_view=instance.MaterializedView(name="name_value"), - materialized_view_id="materialized_view_id_value", + client.get_materialized_view( + bigtable_instance_admin.GetMaterializedViewRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_materialized_view_flattened_async(): +async def test_get_materialized_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.get_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = instance.MaterializedView() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + instance.MaterializedView() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_materialized_view( - parent="parent_value", - materialized_view=instance.MaterializedView(name="name_value"), - materialized_view_id="materialized_view_id_value", + response = await client.get_materialized_view( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].materialized_view - mock_val = instance.MaterializedView(name="name_value") - assert arg == mock_val - arg = args[0].materialized_view_id - mock_val = "materialized_view_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_materialized_view_flattened_error_async(): +async def test_get_materialized_view_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10857,22 +12453,20 @@ async def test_create_materialized_view_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_materialized_view( - bigtable_instance_admin.CreateMaterializedViewRequest(), - parent="parent_value", - materialized_view=instance.MaterializedView(name="name_value"), - materialized_view_id="materialized_view_id_value", + await client.get_materialized_view( + bigtable_instance_admin.GetMaterializedViewRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetMaterializedViewRequest(), + bigtable_instance_admin.ListMaterializedViewsRequest(), {}, ], ) -def test_get_materialized_view(request_type, transport: str = "grpc"): +def test_list_materialized_views(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10884,32 +12478,26 @@ def test_get_materialized_view(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.MaterializedView( - name="name_value", - query="query_value", - etag="etag_value", - deletion_protection=True, + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse( + next_page_token="next_page_token_value", ) - response = client.get_materialized_view(request) + response = client.list_materialized_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.GetMaterializedViewRequest() + request = bigtable_instance_admin.ListMaterializedViewsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.MaterializedView) - assert response.name == "name_value" - assert response.query == "query_value" - assert response.etag == "etag_value" - assert response.deletion_protection is True + assert isinstance(response, pagers.ListMaterializedViewsPager) + assert response.next_page_token == "next_page_token_value" -def test_get_materialized_view_non_empty_request_with_auto_populated_field(): +def test_list_materialized_views_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -10920,27 +12508,29 @@ def test_get_materialized_view_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.GetMaterializedViewRequest( - name="name_value", + request = bigtable_instance_admin.ListMaterializedViewsRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_materialized_view(request=request) + client.list_materialized_views(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetMaterializedViewRequest( - name="name_value", + request_msg = bigtable_instance_admin.ListMaterializedViewsRequest( + parent="parent_value", + page_token="page_token_value", ) assert args[0] == request_msg -def test_get_materialized_view_use_cached_wrapped_rpc(): +def test_list_materialized_views_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10955,7 +12545,7 @@ def test_get_materialized_view_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_materialized_view + client._transport.list_materialized_views in client._transport._wrapped_methods ) @@ -10964,16 +12554,16 @@ def test_get_materialized_view_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_materialized_view] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_materialized_views + ] = mock_rpc request = {} - client.get_materialized_view(request) + client.list_materialized_views(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_materialized_view(request) + client.list_materialized_views(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10981,7 +12571,7 @@ def test_get_materialized_view_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_materialized_view_async_use_cached_wrapped_rpc( +async def test_list_materialized_views_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10998,7 +12588,7 @@ async def test_get_materialized_view_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_materialized_view + client._client._transport.list_materialized_views in client._client._transport._wrapped_methods ) @@ -11006,16 +12596,16 @@ async def test_get_materialized_view_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_materialized_view + client._client._transport.list_materialized_views ] = mock_rpc request = {} - await client.get_materialized_view(request) + await client.list_materialized_views(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_materialized_view(request) + await client.list_materialized_views(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11026,11 +12616,11 @@ async def test_get_materialized_view_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetMaterializedViewRequest(), + bigtable_instance_admin.ListMaterializedViewsRequest(), {}, ], ) -async def test_get_materialized_view_async( +async def test_list_materialized_views_async( request_type, transport: str = "grpc_asyncio" ): client = BigtableInstanceAdminAsyncClient( @@ -11044,50 +12634,44 @@ async def test_get_materialized_view_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.MaterializedView( - name="name_value", - query="query_value", - etag="etag_value", - deletion_protection=True, + bigtable_instance_admin.ListMaterializedViewsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.get_materialized_view(request) + response = await client.list_materialized_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.GetMaterializedViewRequest() + request = bigtable_instance_admin.ListMaterializedViewsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.MaterializedView) - assert response.name == "name_value" - assert response.query == "query_value" - assert response.etag == "etag_value" - assert response.deletion_protection is True + assert isinstance(response, pagers.ListMaterializedViewsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_get_materialized_view_field_headers(): +def test_list_materialized_views_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.GetMaterializedViewRequest() + request = bigtable_instance_admin.ListMaterializedViewsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: - call.return_value = instance.MaterializedView() - client.get_materialized_view(request) + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() + client.list_materialized_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11098,30 +12682,30 @@ def test_get_materialized_view_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_materialized_view_field_headers_async(): +async def test_list_materialized_views_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.GetMaterializedViewRequest() + request = bigtable_instance_admin.ListMaterializedViewsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.MaterializedView() + bigtable_instance_admin.ListMaterializedViewsResponse() ) - await client.get_materialized_view(request) + await client.list_materialized_views(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11132,37 +12716,37 @@ async def test_get_materialized_view_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_materialized_view_flattened(): +def test_list_materialized_views_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.MaterializedView() + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_materialized_view( - name="name_value", + client.list_materialized_views( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_materialized_view_flattened_error(): +def test_list_materialized_views_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11170,45 +12754,45 @@ def test_get_materialized_view_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_materialized_view( - bigtable_instance_admin.GetMaterializedViewRequest(), - name="name_value", + client.list_materialized_views( + bigtable_instance_admin.ListMaterializedViewsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_materialized_view_flattened_async(): +async def test_list_materialized_views_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = instance.MaterializedView() + call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.MaterializedView() + bigtable_instance_admin.ListMaterializedViewsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_materialized_view( - name="name_value", + response = await client.list_materialized_views( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_materialized_view_flattened_error_async(): +async def test_list_materialized_views_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11216,20 +12800,223 @@ async def test_get_materialized_view_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_materialized_view( - bigtable_instance_admin.GetMaterializedViewRequest(), - name="name_value", + await client.list_materialized_views( + bigtable_instance_admin.ListMaterializedViewsRequest(), + parent="parent_value", + ) + + +def test_list_materialized_views_pager(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_materialized_views(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.MaterializedView) for i in results) + + +def test_list_materialized_views_pages(transport_name: str = "grpc"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, + ) + pages = list(client.list_materialized_views(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_materialized_views_async_pager(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_materialized_views( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instance.MaterializedView) for i in responses) + + +@pytest.mark.asyncio +async def test_list_materialized_views_async_pages(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_materialized_views), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + instance.MaterializedView(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMaterializedViewsResponse( + materialized_views=[ + instance.MaterializedView(), + instance.MaterializedView(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_materialized_views(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListMaterializedViewsRequest(), + bigtable_instance_admin.UpdateMaterializedViewRequest(), {}, ], ) -def test_list_materialized_views(request_type, transport: str = "grpc"): +def test_update_materialized_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11241,26 +13028,23 @@ def test_list_materialized_views(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" + type(client.transport.update_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse( - next_page_token="next_page_token_value", - ) - response = client.list_materialized_views(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListMaterializedViewsRequest() + request = bigtable_instance_admin.UpdateMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMaterializedViewsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_materialized_views_non_empty_request_with_auto_populated_field(): +def test_update_materialized_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -11271,29 +13055,23 @@ def test_list_materialized_views_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.ListMaterializedViewsRequest( - parent="parent_value", - page_token="page_token_value", - ) + request = bigtable_instance_admin.UpdateMaterializedViewRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" + type(client.transport.update_materialized_view), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_materialized_views(request=request) + client.update_materialized_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListMaterializedViewsRequest( - parent="parent_value", - page_token="page_token_value", - ) + request_msg = bigtable_instance_admin.UpdateMaterializedViewRequest() assert args[0] == request_msg -def test_list_materialized_views_use_cached_wrapped_rpc(): +def test_update_materialized_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11308,7 +13086,7 @@ def test_list_materialized_views_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_materialized_views + client._transport.update_materialized_view in client._transport._wrapped_methods ) @@ -11318,15 +13096,20 @@ def test_list_materialized_views_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_materialized_views + client._transport.update_materialized_view ] = mock_rpc request = {} - client.list_materialized_views(request) + client.update_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_materialized_views(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11334,7 +13117,7 @@ def test_list_materialized_views_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_materialized_views_async_use_cached_wrapped_rpc( +async def test_update_materialized_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11351,7 +13134,7 @@ async def test_list_materialized_views_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_materialized_views + client._client._transport.update_materialized_view in client._client._transport._wrapped_methods ) @@ -11359,16 +13142,21 @@ async def test_list_materialized_views_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_materialized_views + client._client._transport.update_materialized_view ] = mock_rpc request = {} - await client.list_materialized_views(request) + await client.update_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_materialized_views(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11379,11 +13167,11 @@ async def test_list_materialized_views_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListMaterializedViewsRequest(), + bigtable_instance_admin.UpdateMaterializedViewRequest(), {}, ], ) -async def test_list_materialized_views_async( +async def test_update_materialized_view_async( request_type, transport: str = "grpc_asyncio" ): client = BigtableInstanceAdminAsyncClient( @@ -11397,44 +13185,41 @@ async def test_list_materialized_views_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" + type(client.transport.update_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListMaterializedViewsResponse( - next_page_token="next_page_token_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_materialized_views(request) + response = await client.update_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.ListMaterializedViewsRequest() + request = bigtable_instance_admin.UpdateMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMaterializedViewsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_materialized_views_field_headers(): +def test_update_materialized_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListMaterializedViewsRequest() + request = bigtable_instance_admin.UpdateMaterializedViewRequest() - request.parent = "parent_value" + request.materialized_view.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" + type(client.transport.update_materialized_view), "__call__" ) as call: - call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() - client.list_materialized_views(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11445,341 +13230,148 @@ def test_list_materialized_views_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "materialized_view.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_materialized_views_field_headers_async(): +async def test_update_materialized_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.ListMaterializedViewsRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListMaterializedViewsResponse() - ) - await client.list_materialized_views(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_list_materialized_views_flattened(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_materialized_views( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -def test_list_materialized_views_flattened_error(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_materialized_views( - bigtable_instance_admin.ListMaterializedViewsRequest(), - parent="parent_value", - ) - + request = bigtable_instance_admin.UpdateMaterializedViewRequest() -@pytest.mark.asyncio -async def test_list_materialized_views_flattened_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) + request.materialized_view.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" + type(client.transport.update_materialized_view), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = bigtable_instance_admin.ListMaterializedViewsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListMaterializedViewsResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_materialized_views( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_materialized_views_flattened_error_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_materialized_views( - bigtable_instance_admin.ListMaterializedViewsRequest(), - parent="parent_value", - ) - - -def test_list_materialized_views_pager(transport_name: str = "grpc"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - instance.MaterializedView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_materialized_views(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + operations_pb2.Operation(name="operations/op") + ) + await client.update_materialized_view(request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, instance.MaterializedView) for i in results) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "materialized_view.name=name_value", + ) in kw["metadata"] -def test_list_materialized_views_pages(transport_name: str = "grpc"): +def test_update_materialized_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" + type(client.transport.update_materialized_view), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - instance.MaterializedView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - ], - ), - RuntimeError, + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_materialized_view( + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_materialized_view_flattened_error(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_materialized_view( + bigtable_instance_admin.UpdateMaterializedViewRequest(), + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - pages = list(client.list_materialized_views(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_materialized_views_async_pager(): +async def test_update_materialized_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.update_materialized_view), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - instance.MaterializedView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - ], - ), - RuntimeError, + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - async_pager = await client.list_materialized_views( - request={}, + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_materialized_view( + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - assert len(responses) == 6 - assert all(isinstance(i, instance.MaterializedView) for i in responses) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].materialized_view + mock_val = instance.MaterializedView(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val @pytest.mark.asyncio -async def test_list_materialized_views_async_pages(): +async def test_update_materialized_view_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_materialized_views), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - instance.MaterializedView(), - ], - next_page_token="abc", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[], - next_page_token="def", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - ], - next_page_token="ghi", - ), - bigtable_instance_admin.ListMaterializedViewsResponse( - materialized_views=[ - instance.MaterializedView(), - instance.MaterializedView(), - ], - ), - RuntimeError, + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_materialized_view( + bigtable_instance_admin.UpdateMaterializedViewRequest(), + materialized_view=instance.MaterializedView(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - pages = [] - async for page_ in (await client.list_materialized_views(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.UpdateMaterializedViewRequest(), + bigtable_instance_admin.DeleteMaterializedViewRequest(), {}, ], ) -def test_update_materialized_view(request_type, transport: str = "grpc"): +def test_delete_materialized_view(request_type, transport: str = "grpc"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11791,23 +13383,23 @@ def test_update_materialized_view(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_materialized_view(request) + call.return_value = None + response = client.delete_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.UpdateMaterializedViewRequest() + request = bigtable_instance_admin.DeleteMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert response is None -def test_update_materialized_view_non_empty_request_with_auto_populated_field(): +def test_delete_materialized_view_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = BigtableInstanceAdminClient( @@ -11818,23 +13410,29 @@ def test_update_materialized_view_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.UpdateMaterializedViewRequest() + request = bigtable_instance_admin.DeleteMaterializedViewRequest( + name="name_value", + etag="etag_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_materialized_view(request=request) + client.delete_materialized_view(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.UpdateMaterializedViewRequest() + request_msg = bigtable_instance_admin.DeleteMaterializedViewRequest( + name="name_value", + etag="etag_value", + ) assert args[0] == request_msg -def test_update_materialized_view_use_cached_wrapped_rpc(): +def test_delete_materialized_view_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11849,7 +13447,7 @@ def test_update_materialized_view_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_materialized_view + client._transport.delete_materialized_view in client._transport._wrapped_methods ) @@ -11859,20 +13457,15 @@ def test_update_materialized_view_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_materialized_view + client._transport.delete_materialized_view ] = mock_rpc request = {} - client.update_materialized_view(request) + client.delete_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_materialized_view(request) + client.delete_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11880,7 +13473,7 @@ def test_update_materialized_view_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_materialized_view_async_use_cached_wrapped_rpc( +async def test_delete_materialized_view_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11897,7 +13490,7 @@ async def test_update_materialized_view_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_materialized_view + client._client._transport.delete_materialized_view in client._client._transport._wrapped_methods ) @@ -11905,21 +13498,16 @@ async def test_update_materialized_view_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_materialized_view + client._client._transport.delete_materialized_view ] = mock_rpc request = {} - await client.update_materialized_view(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + await client.delete_materialized_view(request) - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - await client.update_materialized_view(request) + await client.delete_materialized_view(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11930,11 +13518,11 @@ async def test_update_materialized_view_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.UpdateMaterializedViewRequest(), + bigtable_instance_admin.DeleteMaterializedViewRequest(), {}, ], ) -async def test_update_materialized_view_async( +async def test_delete_materialized_view_async( request_type, transport: str = "grpc_asyncio" ): client = BigtableInstanceAdminAsyncClient( @@ -11948,41 +13536,39 @@ async def test_update_materialized_view_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_materialized_view(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.UpdateMaterializedViewRequest() + request = bigtable_instance_admin.DeleteMaterializedViewRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert response is None -def test_update_materialized_view_field_headers(): +def test_delete_materialized_view_field_headers(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.UpdateMaterializedViewRequest() + request = bigtable_instance_admin.DeleteMaterializedViewRequest() - request.materialized_view.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_materialized_view(request) + call.return_value = None + client.delete_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11993,30 +13579,28 @@ def test_update_materialized_view_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "materialized_view.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_materialized_view_field_headers_async(): +async def test_delete_materialized_view_field_headers_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.UpdateMaterializedViewRequest() + request = bigtable_instance_admin.DeleteMaterializedViewRequest() - request.materialized_view.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.update_materialized_view(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_materialized_view(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12027,41 +13611,37 @@ async def test_update_materialized_view_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "materialized_view.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_materialized_view_flattened(): +def test_delete_materialized_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_materialized_view( - materialized_view=instance.MaterializedView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_materialized_view( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].materialized_view - mock_val = instance.MaterializedView(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_materialized_view_flattened_error(): +def test_delete_materialized_view_flattened_error(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12069,50 +13649,43 @@ def test_update_materialized_view_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_materialized_view( - bigtable_instance_admin.UpdateMaterializedViewRequest(), - materialized_view=instance.MaterializedView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_materialized_view( + bigtable_instance_admin.DeleteMaterializedViewRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_materialized_view_flattened_async(): +async def test_delete_materialized_view_flattened_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_materialized_view( - materialized_view=instance.MaterializedView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.delete_materialized_view( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].materialized_view - mock_val = instance.MaterializedView(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_materialized_view_flattened_error_async(): +async def test_delete_materialized_view_flattened_error_async(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12120,88 +13693,196 @@ async def test_update_materialized_view_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_materialized_view( - bigtable_instance_admin.UpdateMaterializedViewRequest(), - materialized_view=instance.MaterializedView(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.delete_materialized_view( + bigtable_instance_admin.DeleteMaterializedViewRequest(), + name="name_value", ) -@pytest.mark.parametrize( - "request_type", - [ - bigtable_instance_admin.DeleteMaterializedViewRequest(), +def test_create_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_instance_rest_required_fields( + request_type=bigtable_instance_admin.CreateInstanceRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateInstance, + "_BaseCreateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", {}, - ], -) -def test_delete_materialized_view(request_type, transport: str = "grpc"): + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" + client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_materialized_view(request) + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_instance_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + instance_id="instance_id_value", + instance=gba_instance.Instance(name="name_value"), + clusters={"key_value": gba_instance.Cluster(name="name_value")}, + ) + mock_args.update(sample_request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.DeleteMaterializedViewRequest() - assert args[0] == request + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the response is the type that we expect. - assert response is None + client.create_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] + ) -def test_delete_materialized_view_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_create_instance_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = bigtable_instance_admin.DeleteMaterializedViewRequest( - name="name_value", - etag="etag_value", + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_materialized_view(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteMaterializedViewRequest( - name="name_value", - etag="etag_value", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_instance( + bigtable_instance_admin.CreateInstanceRequest(), + parent="parent_value", + instance_id="instance_id_value", + instance=gba_instance.Instance(name="name_value"), + clusters={"key_value": gba_instance.Cluster(name="name_value")}, ) - assert args[0] == request_msg -def test_delete_materialized_view_use_cached_wrapped_rpc(): +def test_get_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) # Should wrap all calls on client creation @@ -12209,260 +13890,332 @@ def test_delete_materialized_view_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_materialized_view - in client._transport._wrapped_methods - ) + assert client._transport.get_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.delete_materialized_view - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + request = {} - client.delete_materialized_view(request) + client.get_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_materialized_view(request) + client.get_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_materialized_view_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", +def test_get_instance_rest_required_fields( + request_type=bigtable_instance_admin.GetInstanceRequest, ): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) + transport_class = transports.BigtableInstanceAdminRestTransport - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) - # Ensure method has been cached - assert ( - client._client._transport.delete_materialized_view - in client._client._transport._wrapped_methods - ) + # verify fields with default values are dropped - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_materialized_view - ] = mock_rpc + default_values = getattr( + transport_class._BaseGetInstance, + "_BaseGetInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - request = {} - await client.delete_materialized_view(request) + # verify required fields with default values are now present - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + jsonified_request["name"] = "name_value" - await client.delete_materialized_view(request) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + response_value = Response() + response_value.status_code = 200 -@pytest.mark.asyncio -@pytest.mark.parametrize( - "request_type", - [ - bigtable_instance_admin.DeleteMaterializedViewRequest(), - {}, - ], -) -async def test_delete_materialized_view_async( - request_type, transport: str = "grpc_asyncio" -): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_instance_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Instance() - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_materialized_view(request) + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/instances/sample2"} - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = bigtable_instance_admin.DeleteMaterializedViewRequest() - assert args[0] == request + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] + ) + + +def test_get_instance_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + bigtable_instance_admin.GetInstanceRequest(), + name="name_value", + ) - # Establish that the response is the type that we expect. - assert response is None +def test_list_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -def test_delete_materialized_view_field_headers(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.DeleteMaterializedViewRequest() + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods - request.name = "name_value" + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - call.return_value = None - client.delete_materialized_view(request) + request = {} + client.list_instances(request) # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request + assert mock_rpc.call_count == 1 - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + client.list_instances(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_materialized_view_field_headers_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), + +def test_list_instances_rest_required_fields( + request_type=bigtable_instance_admin.ListInstancesRequest, +): + transport_class = transports.BigtableInstanceAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = bigtable_instance_admin.DeleteMaterializedViewRequest() + # verify fields with default values are dropped - request.name = "name_value" + default_values = getattr( + transport_class._BaseListInstances, + "_BaseListInstances__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_materialized_view(request) + # verify required fields with default values are now present - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request + jsonified_request["parent"] = "parent_value" - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("pageToken",)) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -def test_delete_materialized_view_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_materialized_view( - name="name_value", - ) + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListInstancesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) -def test_delete_materialized_view_flattened_error(): + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_instances_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_materialized_view( - bigtable_instance_admin.DeleteMaterializedViewRequest(), - name="name_value", - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = bigtable_instance_admin.ListInstancesResponse() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} -@pytest.mark.asyncio -async def test_delete_materialized_view_flattened_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_materialized_view( - name="name_value", - ) + client.list_instances(**mock_args) # Establish that the underlying call was made with the expected # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] + ) -@pytest.mark.asyncio -async def test_delete_materialized_view_flattened_error_async(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_materialized_view( - bigtable_instance_admin.DeleteMaterializedViewRequest(), - name="name_value", + client.list_instances( + bigtable_instance_admin.ListInstancesRequest(), + parent="parent_value", ) -def test_create_instance_rest_use_cached_wrapped_rpc(): +def test_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12476,40 +14229,33 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + assert client._transport.update_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc request = {} - client.create_instance(request) + client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_instance(request) + client.update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_instance_rest_required_fields( - request_type=bigtable_instance_admin.CreateInstanceRequest, -): +def test_update_instance_rest_required_fields(request_type=instance.Instance): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" + request_init["display_name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12519,8 +14265,8 @@ def test_create_instance_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateInstance, - "_BaseCreateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateInstance, + "_BaseUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -12530,14 +14276,11 @@ def test_create_instance_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" + jsonified_request["displayName"] = "display_name_value" # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" + assert "displayName" in jsonified_request + assert jsonified_request["displayName"] == "display_name_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12546,7 +14289,7 @@ def test_create_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = instance.Instance() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -12558,7 +14301,7 @@ def test_create_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "put", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -12566,80 +14309,23 @@ def test_create_instance_rest_required_fields( response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_instance(request) + response = client.update_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_instance_rest_flattened(): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - instance_id="instance_id_value", - instance=gba_instance.Instance(name="name_value"), - clusters={"key_value": gba_instance.Cluster(name="name_value")}, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] - ) - - -def test_create_instance_rest_flattened_error(transport: str = "rest"): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_instance( - bigtable_instance_admin.CreateInstanceRequest(), - parent="parent_value", - instance_id="instance_id_value", - instance=gba_instance.Instance(name="name_value"), - clusters={"key_value": gba_instance.Cluster(name="name_value")}, - ) - - -def test_get_instance_rest_use_cached_wrapped_rpc(): +def test_partial_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12653,35 +14339,43 @@ def test_get_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_instance in client._transport._wrapped_methods + assert ( + client._transport.partial_update_instance + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + client._transport._wrapped_methods[ + client._transport.partial_update_instance + ] = mock_rpc request = {} - client.get_instance(request) + client.partial_update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_instance(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.partial_update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_instance_rest_required_fields( - request_type=bigtable_instance_admin.GetInstanceRequest, +def test_partial_update_instance_rest_required_fields( + request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12691,8 +14385,8 @@ def test_get_instance_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetInstance, - "_BaseGetInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BasePartialUpdateInstance, + "_BasePartialUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -12702,11 +14396,10 @@ def test_get_instance_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12715,7 +14408,7 @@ def test_get_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = instance.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -12727,30 +14420,28 @@ def test_get_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_instance(request) + response = client.partial_update_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_instance_rest_flattened(): +def test_partial_update_instance_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12759,39 +14450,39 @@ def test_get_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/instances/sample2"} + sample_request = {"instance": {"name": "projects/sample1/instances/sample2"}} # get truthy value for each flattened field mock_args = dict( - name="name_value", + instance=gba_instance.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_instance(**mock_args) + client.partial_update_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] + "%s/v2/{instance.name=projects/*/instances/*}" % client.transport._host, + args[1], ) -def test_get_instance_rest_flattened_error(transport: str = "rest"): +def test_partial_update_instance_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12800,13 +14491,14 @@ def test_get_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_instance( - bigtable_instance_admin.GetInstanceRequest(), - name="name_value", + client.partial_update_instance( + bigtable_instance_admin.PartialUpdateInstanceRequest(), + instance=gba_instance.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_instances_rest_use_cached_wrapped_rpc(): +def test_delete_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12820,35 +14512,35 @@ def test_list_instances_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_instances in client._transport._wrapped_methods + assert client._transport.delete_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc request = {} - client.list_instances(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_instances(request) + client.delete_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_instances_rest_required_fields( - request_type=bigtable_instance_admin.ListInstancesRequest, +def test_delete_instance_rest_required_fields( + request_type=bigtable_instance_admin.DeleteInstanceRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12858,8 +14550,8 @@ def test_list_instances_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListInstances, - "_BaseListInstances__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteInstance, + "_BaseDeleteInstance__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -12869,14 +14561,11 @@ def test_list_instances_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("pageToken",)) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12885,7 +14574,7 @@ def test_list_instances_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListInstancesResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -12897,32 +14586,27 @@ def test_list_instances_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListInstancesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_instances(request) + response = client.delete_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_instances_rest_flattened(): +def test_delete_instance_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12931,39 +14615,37 @@ def test_list_instances_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListInstancesResponse() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} + sample_request = {"name": "projects/sample1/instances/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_instances(**mock_args) + client.delete_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=projects/*}/instances" % client.transport._host, args[1] + "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] ) -def test_list_instances_rest_flattened_error(transport: str = "rest"): +def test_delete_instance_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12972,13 +14654,13 @@ def test_list_instances_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_instances( - bigtable_instance_admin.ListInstancesRequest(), - parent="parent_value", + client.delete_instance( + bigtable_instance_admin.DeleteInstanceRequest(), + name="name_value", ) -def test_update_instance_rest_use_cached_wrapped_rpc(): +def test_create_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12992,33 +14674,40 @@ def test_update_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + assert client._transport.create_cluster in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc request = {} - client.update_instance(request) + client.create_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_instance(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_instance_rest_required_fields(request_type=instance.Instance): +def test_create_cluster_rest_required_fields( + request_type=bigtable_instance_admin.CreateClusterRequest, +): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["display_name"] = "" + request_init["parent"] = "" + request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13026,10 +14715,11 @@ def test_update_instance_rest_required_fields(request_type=instance.Instance): ) # verify fields with default values are dropped + assert "clusterId" not in jsonified_request default_values = getattr( - transport_class._BaseUpdateInstance, - "_BaseUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateCluster, + "_BaseCreateCluster__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -13038,12 +14728,20 @@ def test_update_instance_rest_required_fields(request_type=instance.Instance): jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] - jsonified_request["displayName"] = "display_name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("clusterId",)) # verify required fields with non-default values are left alone - assert "displayName" in jsonified_request - assert jsonified_request["displayName"] == "display_name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13052,7 +14750,7 @@ def test_update_instance_rest_required_fields(request_type=instance.Instance): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = instance.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13064,7 +14762,7 @@ def test_update_instance_rest_required_fields(request_type=instance.Instance): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "put", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -13072,23 +14770,85 @@ def test_update_instance_rest_required_fields(request_type=instance.Instance): response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_instance(request) + response = client.create_cluster(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_partial_update_instance_rest_use_cached_wrapped_rpc(): +def test_create_cluster_rest_flattened(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/instances/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + cluster_id="cluster_id_value", + cluster=instance.Cluster(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, + args[1], + ) + + +def test_create_cluster_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_cluster( + bigtable_instance_admin.CreateClusterRequest(), + parent="parent_value", + cluster_id="cluster_id_value", + cluster=instance.Cluster(name="name_value"), + ) + + +def test_get_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13102,43 +14862,35 @@ def test_partial_update_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.partial_update_instance - in client._transport._wrapped_methods - ) + assert client._transport.get_cluster in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.partial_update_instance - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc request = {} - client.partial_update_instance(request) + client.get_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.partial_update_instance(request) + client.get_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_partial_update_instance_rest_required_fields( - request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, +def test_get_cluster_rest_required_fields( + request_type=bigtable_instance_admin.GetClusterRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13148,8 +14900,8 @@ def test_partial_update_instance_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BasePartialUpdateInstance, - "_BasePartialUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetCluster, + "_BaseGetCluster__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -13159,10 +14911,11 @@ def test_partial_update_instance_rest_required_fields( # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("updateMask",)) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13171,7 +14924,7 @@ def test_partial_update_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = instance.Cluster() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13183,28 +14936,30 @@ def test_partial_update_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Cluster.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.partial_update_instance(request) + response = client.get_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_partial_update_instance_rest_flattened(): +def test_get_cluster_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13213,39 +14968,40 @@ def test_partial_update_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = instance.Cluster() # get arguments that satisfy an http rule for this method - sample_request = {"instance": {"name": "projects/sample1/instances/sample2"}} + sample_request = {"name": "projects/sample1/instances/sample2/clusters/sample3"} # get truthy value for each flattened field mock_args = dict( - instance=gba_instance.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.Cluster.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.partial_update_instance(**mock_args) + client.get_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{instance.name=projects/*/instances/*}" % client.transport._host, + "%s/v2/{name=projects/*/instances/*/clusters/*}" % client.transport._host, args[1], ) -def test_partial_update_instance_rest_flattened_error(transport: str = "rest"): +def test_get_cluster_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13254,14 +15010,13 @@ def test_partial_update_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.partial_update_instance( - bigtable_instance_admin.PartialUpdateInstanceRequest(), - instance=gba_instance.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_cluster( + bigtable_instance_admin.GetClusterRequest(), + name="name_value", ) -def test_delete_instance_rest_use_cached_wrapped_rpc(): +def test_list_clusters_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13275,35 +15030,35 @@ def test_delete_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods + assert client._transport.list_clusters in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc request = {} - client.delete_instance(request) + client.list_clusters(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_instance(request) + client.list_clusters(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_instance_rest_required_fields( - request_type=bigtable_instance_admin.DeleteInstanceRequest, +def test_list_clusters_rest_required_fields( + request_type=bigtable_instance_admin.ListClustersRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13313,8 +15068,8 @@ def test_delete_instance_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteInstance, - "_BaseDeleteInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListClusters, + "_BaseListClusters__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -13324,11 +15079,14 @@ def test_delete_instance_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("pageToken",)) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13337,7 +15095,7 @@ def test_delete_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = bigtable_instance_admin.ListClustersResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13349,27 +15107,30 @@ def test_delete_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_instance(request) + response = client.list_clusters(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_instance_rest_flattened(): +def test_list_clusters_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13378,37 +15139,40 @@ def test_delete_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = bigtable_instance_admin.ListClustersResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/instances/sample2"} + sample_request = {"parent": "projects/sample1/instances/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_instance(**mock_args) + client.list_clusters(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/instances/*}" % client.transport._host, args[1] + "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, + args[1], ) -def test_delete_instance_rest_flattened_error(transport: str = "rest"): +def test_list_clusters_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13417,13 +15181,13 @@ def test_delete_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_instance( - bigtable_instance_admin.DeleteInstanceRequest(), - name="name_value", + client.list_clusters( + bigtable_instance_admin.ListClustersRequest(), + parent="parent_value", ) -def test_create_cluster_rest_use_cached_wrapped_rpc(): +def test_update_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13437,17 +15201,62 @@ def test_create_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_cluster in client._transport._wrapped_methods + assert client._transport.update_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc + + request = {} + client.update_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_partial_update_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.partial_update_cluster + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc + client._transport._wrapped_methods[client._transport.partial_update_cluster] = ( + mock_rpc + ) request = {} - client.create_cluster(request) + client.partial_update_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -13456,21 +15265,19 @@ def test_create_cluster_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_cluster(request) + client.partial_update_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_cluster_rest_required_fields( - request_type=bigtable_instance_admin.CreateClusterRequest, +def test_partial_update_cluster_rest_required_fields( + request_type=bigtable_instance_admin.PartialUpdateClusterRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13478,11 +15285,10 @@ def test_create_cluster_rest_required_fields( ) # verify fields with default values are dropped - assert "clusterId" not in jsonified_request default_values = getattr( - transport_class._BaseCreateCluster, - "_BaseCreateCluster__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BasePartialUpdateCluster, + "_BasePartialUpdateCluster__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -13491,20 +15297,11 @@ def test_create_cluster_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("clusterId",)) + assert not set(unset_fields) - set(("updateMask",)) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13525,7 +15322,7 @@ def test_create_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -13539,20 +15336,14 @@ def test_create_cluster_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_cluster(request) + response = client.partial_update_cluster(request) - expected_params = [ - ( - "clusterId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_cluster_rest_flattened(): +def test_partial_update_cluster_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13564,13 +15355,14 @@ def test_create_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/instances/sample2"} + sample_request = { + "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - cluster_id="cluster_id_value", cluster=instance.Cluster(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -13582,19 +15374,20 @@ def test_create_cluster_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_cluster(**mock_args) + client.partial_update_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, + "%s/v2/{cluster.name=projects/*/instances/*/clusters/*}" + % client.transport._host, args[1], ) -def test_create_cluster_rest_flattened_error(transport: str = "rest"): +def test_partial_update_cluster_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13603,15 +15396,14 @@ def test_create_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_cluster( - bigtable_instance_admin.CreateClusterRequest(), - parent="parent_value", - cluster_id="cluster_id_value", + client.partial_update_cluster( + bigtable_instance_admin.PartialUpdateClusterRequest(), cluster=instance.Cluster(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_cluster_rest_use_cached_wrapped_rpc(): +def test_delete_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13625,30 +15417,30 @@ def test_get_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_cluster in client._transport._wrapped_methods + assert client._transport.delete_cluster in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc request = {} - client.get_cluster(request) + client.delete_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_cluster(request) + client.delete_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_cluster_rest_required_fields( - request_type=bigtable_instance_admin.GetClusterRequest, +def test_delete_cluster_rest_required_fields( + request_type=bigtable_instance_admin.DeleteClusterRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport @@ -13663,8 +15455,8 @@ def test_get_cluster_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetCluster, - "_BaseGetCluster__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteCluster, + "_BaseDeleteCluster__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -13687,7 +15479,7 @@ def test_get_cluster_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = instance.Cluster() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13699,30 +15491,27 @@ def test_get_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_cluster(request) + response = client.delete_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_cluster_rest_flattened(): +def test_delete_cluster_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13731,7 +15520,7 @@ def test_get_cluster_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.Cluster() + return_value = None # get arguments that satisfy an http rule for this method sample_request = {"name": "projects/sample1/instances/sample2/clusters/sample3"} @@ -13745,14 +15534,12 @@ def test_get_cluster_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_cluster(**mock_args) + client.delete_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -13764,7 +15551,7 @@ def test_get_cluster_rest_flattened(): ) -def test_get_cluster_rest_flattened_error(transport: str = "rest"): +def test_delete_cluster_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13773,13 +15560,13 @@ def test_get_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_cluster( - bigtable_instance_admin.GetClusterRequest(), + client.delete_cluster( + bigtable_instance_admin.DeleteClusterRequest(), name="name_value", ) -def test_list_clusters_rest_use_cached_wrapped_rpc(): +def test_update_memory_layer_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13793,35 +15580,42 @@ def test_list_clusters_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_clusters in client._transport._wrapped_methods + assert ( + client._transport.update_memory_layer in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc + client._transport._wrapped_methods[client._transport.update_memory_layer] = ( + mock_rpc + ) request = {} - client.list_clusters(request) + client.update_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_clusters(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_memory_layer(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_clusters_rest_required_fields( - request_type=bigtable_instance_admin.ListClustersRequest, +def test_update_memory_layer_rest_required_fields( + request_type=bigtable_instance_admin.UpdateMemoryLayerRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13831,8 +15625,8 @@ def test_list_clusters_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListClusters, - "_BaseListClusters__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateMemoryLayer, + "_BaseUpdateMemoryLayer__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -13842,14 +15636,10 @@ def test_list_clusters_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("pageToken",)) + assert not set(unset_fields) - set(("updateMask",)) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13858,7 +15648,7 @@ def test_list_clusters_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListClustersResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13870,30 +15660,28 @@ def test_list_clusters_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_clusters(request) + response = client.update_memory_layer(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_clusters_rest_flattened(): +def test_update_memory_layer_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13902,40 +15690,44 @@ def test_list_clusters_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListClustersResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/instances/sample2"} + sample_request = { + "memory_layer": { + "name": "projects/sample1/instances/sample2/clusters/sample3/memoryLayer" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + memory_layer=instance.MemoryLayer(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_clusters(**mock_args) + client.update_memory_layer(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=projects/*/instances/*}/clusters" % client.transport._host, + "%s/v2/{memory_layer.name=projects/*/instances/*/clusters/*/memoryLayer}" + % client.transport._host, args[1], ) -def test_list_clusters_rest_flattened_error(transport: str = "rest"): +def test_update_memory_layer_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13944,53 +15736,14 @@ def test_list_clusters_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_clusters( - bigtable_instance_admin.ListClustersRequest(), - parent="parent_value", - ) - - -def test_update_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + client.update_memory_layer( + bigtable_instance_admin.UpdateMemoryLayerRequest(), + memory_layer=instance.MemoryLayer(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc - - request = {} - client.update_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 -def test_partial_update_cluster_rest_use_cached_wrapped_rpc(): +def test_list_memory_layers_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14005,8 +15758,7 @@ def test_partial_update_cluster_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.partial_update_cluster - in client._transport._wrapped_methods + client._transport.list_memory_layers in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -14014,33 +15766,30 @@ def test_partial_update_cluster_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.partial_update_cluster] = ( + client._transport._wrapped_methods[client._transport.list_memory_layers] = ( mock_rpc ) request = {} - client.partial_update_cluster(request) + client.list_memory_layers(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.partial_update_cluster(request) + client.list_memory_layers(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_partial_update_cluster_rest_required_fields( - request_type=bigtable_instance_admin.PartialUpdateClusterRequest, +def test_list_memory_layers_rest_required_fields( + request_type=bigtable_instance_admin.ListMemoryLayersRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14050,8 +15799,8 @@ def test_partial_update_cluster_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BasePartialUpdateCluster, - "_BasePartialUpdateCluster__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListMemoryLayers, + "_BaseListMemoryLayers__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -14061,10 +15810,19 @@ def test_partial_update_cluster_rest_required_fields( # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("updateMask",)) + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14073,7 +15831,7 @@ def test_partial_update_cluster_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = bigtable_instance_admin.ListMemoryLayersResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14085,28 +15843,32 @@ def test_partial_update_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListMemoryLayersResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.partial_update_cluster(request) + response = client.list_memory_layers(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_partial_update_cluster_rest_flattened(): +def test_list_memory_layers_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14115,58 +15877,127 @@ def test_partial_update_cluster_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = bigtable_instance_admin.ListMemoryLayersResponse() # get arguments that satisfy an http rule for this method sample_request = { - "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + "parent": "projects/sample1/instances/sample2/clusters/sample3" } # get truthy value for each flattened field mock_args = dict( - cluster=instance.Cluster(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListMemoryLayersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.partial_update_cluster(**mock_args) + client.list_memory_layers(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{cluster.name=projects/*/instances/*/clusters/*}" + "%s/v2/{parent=projects/*/instances/*/clusters/*}/memoryLayers" % client.transport._host, args[1], ) -def test_partial_update_cluster_rest_flattened_error(transport: str = "rest"): +def test_list_memory_layers_rest_flattened_error(transport: str = "rest"): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_memory_layers( + bigtable_instance_admin.ListMemoryLayersRequest(), + parent="parent_value", + ) + + +def test_list_memory_layers_rest_pager(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.partial_update_cluster( - bigtable_instance_admin.PartialUpdateClusterRequest(), - cluster=instance.Cluster(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + next_page_token="abc", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[], + next_page_token="def", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + ], + next_page_token="ghi", + ), + bigtable_instance_admin.ListMemoryLayersResponse( + memory_layers=[ + instance.MemoryLayer(), + instance.MemoryLayer(), + ], + ), ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bigtable_instance_admin.ListMemoryLayersResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + sample_request = { + "parent": "projects/sample1/instances/sample2/clusters/sample3" + } -def test_delete_cluster_rest_use_cached_wrapped_rpc(): + pager = client.list_memory_layers(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.MemoryLayer) for i in results) + + pages = list(client.list_memory_layers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_memory_layer_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14180,30 +16011,32 @@ def test_delete_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_cluster in client._transport._wrapped_methods + assert client._transport.get_memory_layer in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc + client._transport._wrapped_methods[client._transport.get_memory_layer] = ( + mock_rpc + ) request = {} - client.delete_cluster(request) + client.get_memory_layer(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_cluster(request) + client.get_memory_layer(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_cluster_rest_required_fields( - request_type=bigtable_instance_admin.DeleteClusterRequest, +def test_get_memory_layer_rest_required_fields( + request_type=bigtable_instance_admin.GetMemoryLayerRequest, ): transport_class = transports.BigtableInstanceAdminRestTransport @@ -14218,8 +16051,8 @@ def test_delete_cluster_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteCluster, - "_BaseDeleteCluster__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetMemoryLayer, + "_BaseGetMemoryLayer__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -14242,7 +16075,7 @@ def test_delete_cluster_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = instance.MemoryLayer() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14254,27 +16087,30 @@ def test_delete_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = instance.MemoryLayer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_cluster(request) + response = client.get_memory_layer(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_cluster_rest_flattened(): +def test_get_memory_layer_rest_flattened(): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14283,10 +16119,12 @@ def test_delete_cluster_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = instance.MemoryLayer() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + sample_request = { + "name": "projects/sample1/instances/sample2/clusters/sample3/memoryLayer" + } # get truthy value for each flattened field mock_args = dict( @@ -14297,24 +16135,27 @@ def test_delete_cluster_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = instance.MemoryLayer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_cluster(**mock_args) + client.get_memory_layer(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/instances/*/clusters/*}" % client.transport._host, + "%s/v2/{name=projects/*/instances/*/clusters/*/memoryLayer}" + % client.transport._host, args[1], ) -def test_delete_cluster_rest_flattened_error(transport: str = "rest"): +def test_get_memory_layer_rest_flattened_error(transport: str = "rest"): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14323,8 +16164,8 @@ def test_delete_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_cluster( - bigtable_instance_admin.DeleteClusterRequest(), + client.get_memory_layer( + bigtable_instance_admin.GetMemoryLayerRequest(), name="name_value", ) @@ -18370,6 +20211,70 @@ def test_delete_cluster_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_memory_layer_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_memory_layer), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_memory_layer(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateMemoryLayerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_memory_layers_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: + call.return_value = bigtable_instance_admin.ListMemoryLayersResponse() + client.list_memory_layers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListMemoryLayersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_memory_layer_empty_call_grpc(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: + call.return_value = instance.MemoryLayer() + client.get_memory_layer(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetMemoryLayerRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_app_profile_empty_call_grpc(): @@ -19109,6 +21014,89 @@ async def test_delete_cluster_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_memory_layer_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_memory_layer), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_memory_layer(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateMemoryLayerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_memory_layers_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigtable_instance_admin.ListMemoryLayersResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) + ) + await client.list_memory_layers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListMemoryLayersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_memory_layer_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.MemoryLayer( + name="name_value", + etag="etag_value", + state=instance.MemoryLayer.State.READY, + ) + ) + await client.get_memory_layer(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetMemoryLayerRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -19483,14 +21471,71 @@ async def test_delete_logical_view_empty_call_grpc_asyncio(): # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteLogicalViewRequest() + request_msg = bigtable_instance_admin.DeleteLogicalViewRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_materialized_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.CreateMaterializedViewRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_materialized_view_empty_call_grpc_asyncio(): + client = BigtableInstanceAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_materialized_view), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.MaterializedView( + name="name_value", + query="query_value", + etag="etag_value", + deletion_protection=True, + ) + ) + await client.get_materialized_view(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetMaterializedViewRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_create_materialized_view_empty_call_grpc_asyncio(): +async def test_list_materialized_views_empty_call_grpc_asyncio(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", @@ -19498,25 +21543,27 @@ async def test_create_materialized_view_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_materialized_view), "__call__" + type(client.transport.list_materialized_views), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + bigtable_instance_admin.ListMaterializedViewsResponse( + next_page_token="next_page_token_value", + ) ) - await client.create_materialized_view(request=None) + await client.list_materialized_views(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.CreateMaterializedViewRequest() + request_msg = bigtable_instance_admin.ListMaterializedViewsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_materialized_view_empty_call_grpc_asyncio(): +async def test_update_materialized_view_empty_call_grpc_asyncio(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", @@ -19524,30 +21571,25 @@ async def test_get_materialized_view_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_materialized_view), "__call__" + type(client.transport.update_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.MaterializedView( - name="name_value", - query="query_value", - etag="etag_value", - deletion_protection=True, - ) + operations_pb2.Operation(name="operations/spam") ) - await client.get_materialized_view(request=None) + await client.update_materialized_view(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.GetMaterializedViewRequest() + request_msg = bigtable_instance_admin.UpdateMaterializedViewRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_materialized_views_empty_call_grpc_asyncio(): +async def test_delete_materialized_view_empty_call_grpc_asyncio(): client = BigtableInstanceAdminAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", @@ -19555,82 +21597,297 @@ async def test_list_materialized_views_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_materialized_views), "__call__" + type(client.transport.delete_materialized_view), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bigtable_instance_admin.ListMaterializedViewsResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_materialized_views(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_materialized_view(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.ListMaterializedViewsRequest() + request_msg = bigtable_instance_admin.DeleteMaterializedViewRequest() assert args[0] == request_msg -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_materialized_view_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_transport_kind_rest(): + transport = BigtableInstanceAdminClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_instance_rest_bad_request( + request_type=bigtable_instance_admin.CreateInstanceRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_create_instance" + ) as post, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_create_instance_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_create_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.CreateInstanceRequest.pb( + bigtable_instance_admin.CreateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = bigtable_instance_admin.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_instance_rest_bad_request( + request_type=bigtable_instance_admin.GetInstanceRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/instances/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Instance( + name="name_value", + display_name="display_name_value", + state=instance.Instance.State.READY, + type_=instance.Instance.Type.PRODUCTION, + edition=instance.Instance.Edition.ENTERPRISE, + satisfies_pzs=True, + satisfies_pzi=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.state == instance.Instance.State.READY + assert response.type_ == instance.Instance.Type.PRODUCTION + assert response.edition == instance.Instance.Edition.ENTERPRISE + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), ) + client = BigtableInstanceAdminClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_materialized_view), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_get_instance" + ) as post, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_get_instance_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetInstanceRequest.pb( + bigtable_instance_admin.GetInstanceRequest() ) - await client.update_materialized_view(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.UpdateMaterializedViewRequest() - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_materialized_view_empty_call_grpc_asyncio(): - client = BigtableInstanceAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_materialized_view), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_materialized_view(request=None) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.Instance.to_json(instance.Instance()) + req.return_value.content = return_value - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bigtable_instance_admin.DeleteMaterializedViewRequest() - assert args[0] == request_msg + request = bigtable_instance_admin.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.Instance() + post_with_metadata.return_value = instance.Instance(), metadata + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = BigtableInstanceAdminClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_create_instance_rest_bad_request( - request_type=bigtable_instance_admin.CreateInstanceRequest, +def test_list_instances_rest_bad_request( + request_type=bigtable_instance_admin.ListInstancesRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -19652,17 +21909,17 @@ def test_create_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_instance(request) + client.list_instances(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateInstanceRequest, + bigtable_instance_admin.ListInstancesRequest, dict, ], ) -def test_create_instance_rest_call_success(request_type): +def test_list_instances_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -19674,23 +21931,33 @@ def test_create_instance_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = bigtable_instance_admin.ListInstancesResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_instance(request) + response = client.list_instances(request) + + assert response.raw_page is response # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, bigtable_instance_admin.ListInstancesResponse) + assert response.failed_locations == ["failed_locations_value"] + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): +def test_list_instances_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19702,23 +21969,22 @@ def test_create_instance_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_create_instance" + transports.BigtableInstanceAdminRestInterceptor, "post_list_instances" ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_create_instance_with_metadata", + "post_list_instances_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_create_instance" + transports.BigtableInstanceAdminRestInterceptor, "pre_list_instances" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.CreateInstanceRequest.pb( - bigtable_instance_admin.CreateInstanceRequest() + pb_message = bigtable_instance_admin.ListInstancesRequest.pb( + bigtable_instance_admin.ListInstancesRequest() ) transcode.return_value = { "method": "post", @@ -19730,19 +21996,24 @@ def test_create_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = bigtable_instance_admin.ListInstancesResponse.to_json( + bigtable_instance_admin.ListInstancesResponse() + ) req.return_value.content = return_value - request = bigtable_instance_admin.CreateInstanceRequest() + request = bigtable_instance_admin.ListInstancesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = bigtable_instance_admin.ListInstancesResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListInstancesResponse(), + metadata, + ) - client.create_instance( + client.list_instances( request, metadata=[ ("key", "val"), @@ -19755,9 +22026,7 @@ def test_create_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_instance_rest_bad_request( - request_type=bigtable_instance_admin.GetInstanceRequest, -): +def test_update_instance_rest_bad_request(request_type=instance.Instance): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -19778,17 +22047,17 @@ def test_get_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_instance(request) + client.update_instance(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetInstanceRequest, + instance.Instance, dict, ], ) -def test_get_instance_rest_call_success(request_type): +def test_update_instance_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -19820,7 +22089,7 @@ def test_get_instance_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_instance(request) + response = client.update_instance(request) # Establish that the response is the type that we expect. assert isinstance(response, instance.Instance) @@ -19834,7 +22103,7 @@ def test_get_instance_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): +def test_update_instance_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19847,22 +22116,20 @@ def test_get_instance_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_get_instance" + transports.BigtableInstanceAdminRestInterceptor, "post_update_instance" ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_get_instance_with_metadata", + "post_update_instance_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_get_instance" + transports.BigtableInstanceAdminRestInterceptor, "pre_update_instance" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.GetInstanceRequest.pb( - bigtable_instance_admin.GetInstanceRequest() - ) + pb_message = instance.Instance.pb(instance.Instance()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19876,7 +22143,7 @@ def test_get_instance_rest_interceptors(null_interceptor): return_value = instance.Instance.to_json(instance.Instance()) req.return_value.content = return_value - request = bigtable_instance_admin.GetInstanceRequest() + request = instance.Instance() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -19885,7 +22152,7 @@ def test_get_instance_rest_interceptors(null_interceptor): post.return_value = instance.Instance() post_with_metadata.return_value = instance.Instance(), metadata - client.get_instance( + client.update_instance( request, metadata=[ ("key", "val"), @@ -19898,78 +22165,149 @@ def test_get_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_instances_rest_bad_request( - request_type=bigtable_instance_admin.ListInstancesRequest, -): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - request = request_type(**request_init) +def test_partial_update_instance_rest_bad_request( + request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.partial_update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.PartialUpdateInstanceRequest, + dict, + ], +) +def test_partial_update_instance_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} + request_init["instance"] = { + "name": "projects/sample1/instances/sample2", + "display_name": "display_name_value", + "state": 1, + "type_": 1, + "edition": 1, + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "satisfies_pzs": True, + "satisfies_pzi": True, + "tags": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = bigtable_instance_admin.PartialUpdateInstanceRequest.meta.fields[ + "instance" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_instances(request) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - bigtable_instance_admin.ListInstancesRequest, - dict, - ], -) -def test_list_instances_rest_call_success(request_type): - client = BigtableInstanceAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListInstancesResponse( - failed_locations=["failed_locations_value"], - next_page_token="next_page_token_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListInstancesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_instances(request) - - assert response.raw_page is response + response = client.partial_update_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, bigtable_instance_admin.ListInstancesResponse) - assert response.failed_locations == ["failed_locations_value"] - assert response.next_page_token == "next_page_token_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): +def test_partial_update_instance_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19981,22 +22319,25 @@ def test_list_instances_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_list_instances" + transports.BigtableInstanceAdminRestInterceptor, + "post_partial_update_instance", ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_list_instances_with_metadata", + "post_partial_update_instance_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_list_instances" + transports.BigtableInstanceAdminRestInterceptor, + "pre_partial_update_instance", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.ListInstancesRequest.pb( - bigtable_instance_admin.ListInstancesRequest() + pb_message = bigtable_instance_admin.PartialUpdateInstanceRequest.pb( + bigtable_instance_admin.PartialUpdateInstanceRequest() ) transcode.return_value = { "method": "post", @@ -20008,24 +22349,19 @@ def test_list_instances_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = bigtable_instance_admin.ListInstancesResponse.to_json( - bigtable_instance_admin.ListInstancesResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.ListInstancesRequest() + request = bigtable_instance_admin.PartialUpdateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = bigtable_instance_admin.ListInstancesResponse() - post_with_metadata.return_value = ( - bigtable_instance_admin.ListInstancesResponse(), - metadata, - ) + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_instances( + client.partial_update_instance( request, metadata=[ ("key", "val"), @@ -20038,7 +22374,9 @@ def test_list_instances_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_instance_rest_bad_request(request_type=instance.Instance): +def test_delete_instance_rest_bad_request( + request_type=bigtable_instance_admin.DeleteInstanceRequest, +): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -20059,17 +22397,17 @@ def test_update_instance_rest_bad_request(request_type=instance.Instance): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_instance(request) + client.delete_instance(request) @pytest.mark.parametrize( "request_type", [ - instance.Instance, + bigtable_instance_admin.DeleteInstanceRequest, dict, ], ) -def test_update_instance_rest_call_success(request_type): +def test_delete_instance_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -20081,41 +22419,23 @@ def test_update_instance_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.Instance( - name="name_value", - display_name="display_name_value", - state=instance.Instance.State.READY, - type_=instance.Instance.Type.PRODUCTION, - edition=instance.Instance.Edition.ENTERPRISE, - satisfies_pzs=True, - satisfies_pzi=True, - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_instance(request) + response = client.delete_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, instance.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.state == instance.Instance.State.READY - assert response.type_ == instance.Instance.Type.PRODUCTION - assert response.edition == instance.Instance.Edition.ENTERPRISE - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): +def test_delete_instance_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20128,20 +22448,13 @@ def test_update_instance_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_update_instance" - ) as post, - mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, - "post_update_instance_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_update_instance" + transports.BigtableInstanceAdminRestInterceptor, "pre_delete_instance" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = instance.Instance.pb(instance.Instance()) + pb_message = bigtable_instance_admin.DeleteInstanceRequest.pb( + bigtable_instance_admin.DeleteInstanceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20152,19 +22465,15 @@ def test_update_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = instance.Instance.to_json(instance.Instance()) - req.return_value.content = return_value - request = instance.Instance() + request = bigtable_instance_admin.DeleteInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = instance.Instance() - post_with_metadata.return_value = instance.Instance(), metadata - client.update_instance( + client.delete_instance( request, metadata=[ ("key", "val"), @@ -20173,18 +22482,16 @@ def test_update_instance_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_partial_update_instance_rest_bad_request( - request_type=bigtable_instance_admin.PartialUpdateInstanceRequest, +def test_create_cluster_rest_bad_request( + request_type=bigtable_instance_admin.CreateClusterRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} + request_init = {"parent": "projects/sample1/instances/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -20200,43 +22507,50 @@ def test_partial_update_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.partial_update_instance(request) + client.create_cluster(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.PartialUpdateInstanceRequest, + bigtable_instance_admin.CreateClusterRequest, dict, ], ) -def test_partial_update_instance_rest_call_success(request_type): +def test_create_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"instance": {"name": "projects/sample1/instances/sample2"}} - request_init["instance"] = { - "name": "projects/sample1/instances/sample2", - "display_name": "display_name_value", + request_init = {"parent": "projects/sample1/instances/sample2"} + request_init["cluster"] = { + "name": "name_value", + "location": "location_value", "state": 1, - "type_": 1, - "edition": 1, - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "satisfies_pzs": True, - "satisfies_pzi": True, - "tags": {}, + "serve_nodes": 1181, + "node_scaling_factor": 1, + "cluster_config": { + "cluster_autoscaling_config": { + "autoscaling_limits": { + "min_serve_nodes": 1600, + "max_serve_nodes": 1602, + }, + "autoscaling_targets": { + "cpu_utilization_percent": 2483, + "storage_utilization_gib_per_node": 3404, + }, + } + }, + "default_storage_type": 1, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.PartialUpdateInstanceRequest.meta.fields[ - "instance" - ] + test_field = bigtable_instance_admin.CreateClusterRequest.meta.fields["cluster"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -20264,7 +22578,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER + for field, value in request_init["cluster"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -20294,10 +22608,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] else: - del request_init["instance"][field][subfield] + del request_init["cluster"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -20312,14 +22626,14 @@ def get_message_fields(field): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.partial_update_instance(request) + response = client.create_cluster(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_partial_update_instance_rest_interceptors(null_interceptor): +def test_create_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20333,23 +22647,21 @@ def test_partial_update_instance_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, - "post_partial_update_instance", + transports.BigtableInstanceAdminRestInterceptor, "post_create_cluster" ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_partial_update_instance_with_metadata", + "post_create_cluster_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, - "pre_partial_update_instance", + transports.BigtableInstanceAdminRestInterceptor, "pre_create_cluster" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.PartialUpdateInstanceRequest.pb( - bigtable_instance_admin.PartialUpdateInstanceRequest() + pb_message = bigtable_instance_admin.CreateClusterRequest.pb( + bigtable_instance_admin.CreateClusterRequest() ) transcode.return_value = { "method": "post", @@ -20364,7 +22676,7 @@ def test_partial_update_instance_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.PartialUpdateInstanceRequest() + request = bigtable_instance_admin.CreateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -20373,7 +22685,7 @@ def test_partial_update_instance_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.partial_update_instance( + client.create_cluster( request, metadata=[ ("key", "val"), @@ -20386,14 +22698,14 @@ def test_partial_update_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_instance_rest_bad_request( - request_type=bigtable_instance_admin.DeleteInstanceRequest, +def test_get_cluster_rest_bad_request( + request_type=bigtable_instance_admin.GetClusterRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -20409,45 +22721,64 @@ def test_delete_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_instance(request) + client.get_cluster(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteInstanceRequest, + bigtable_instance_admin.GetClusterRequest, dict, ], ) -def test_delete_instance_rest_call_success(request_type): +def test_get_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2"} + request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = instance.Cluster( + name="name_value", + location="location_value", + state=instance.Cluster.State.READY, + serve_nodes=1181, + node_scaling_factor=instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X, + default_storage_type=common.StorageType.SSD, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = instance.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_instance(request) + response = client.get_cluster(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, instance.Cluster) + assert response.name == "name_value" + assert response.location == "location_value" + assert response.state == instance.Cluster.State.READY + assert response.serve_nodes == 1181 + assert ( + response.node_scaling_factor + == instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X + ) + assert response.default_storage_type == common.StorageType.SSD @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): +def test_get_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20460,12 +22791,21 @@ def test_delete_instance_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_delete_instance" + transports.BigtableInstanceAdminRestInterceptor, "post_get_cluster" + ) as post, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_get_cluster_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_cluster" ) as pre, ): pre.assert_not_called() - pb_message = bigtable_instance_admin.DeleteInstanceRequest.pb( - bigtable_instance_admin.DeleteInstanceRequest() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetClusterRequest.pb( + bigtable_instance_admin.GetClusterRequest() ) transcode.return_value = { "method": "post", @@ -20477,15 +22817,19 @@ def test_delete_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.Cluster.to_json(instance.Cluster()) + req.return_value.content = return_value - request = bigtable_instance_admin.DeleteInstanceRequest() + request = bigtable_instance_admin.GetClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = instance.Cluster() + post_with_metadata.return_value = instance.Cluster(), metadata - client.delete_instance( + client.get_cluster( request, metadata=[ ("key", "val"), @@ -20494,10 +22838,12 @@ def test_delete_instance_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_create_cluster_rest_bad_request( - request_type=bigtable_instance_admin.CreateClusterRequest, +def test_list_clusters_rest_bad_request( + request_type=bigtable_instance_admin.ListClustersRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -20519,133 +22865,55 @@ def test_create_cluster_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_cluster(request) + client.list_clusters(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.CreateClusterRequest, + bigtable_instance_admin.ListClustersRequest, dict, ], ) -def test_create_cluster_rest_call_success(request_type): +def test_list_clusters_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/instances/sample2"} - request_init["cluster"] = { - "name": "name_value", - "location": "location_value", - "state": 1, - "serve_nodes": 1181, - "node_scaling_factor": 1, - "cluster_config": { - "cluster_autoscaling_config": { - "autoscaling_limits": { - "min_serve_nodes": 1600, - "max_serve_nodes": 1602, - }, - "autoscaling_targets": { - "cpu_utilization_percent": 2483, - "storage_utilization_gib_per_node": 3404, - }, - } - }, - "default_storage_type": 1, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.CreateClusterRequest.meta.fields["cluster"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = bigtable_instance_admin.ListClustersResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_cluster(request) + response = client.list_clusters(request) + + assert response.raw_page is response # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, bigtable_instance_admin.ListClustersResponse) + assert response.failed_locations == ["failed_locations_value"] + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): +def test_list_clusters_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20657,23 +22925,22 @@ def test_create_cluster_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_create_cluster" + transports.BigtableInstanceAdminRestInterceptor, "post_list_clusters" ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_create_cluster_with_metadata", + "post_list_clusters_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_create_cluster" + transports.BigtableInstanceAdminRestInterceptor, "pre_list_clusters" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.CreateClusterRequest.pb( - bigtable_instance_admin.CreateClusterRequest() + pb_message = bigtable_instance_admin.ListClustersRequest.pb( + bigtable_instance_admin.ListClustersRequest() ) transcode.return_value = { "method": "post", @@ -20685,19 +22952,24 @@ def test_create_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = bigtable_instance_admin.ListClustersResponse.to_json( + bigtable_instance_admin.ListClustersResponse() + ) req.return_value.content = return_value - request = bigtable_instance_admin.CreateClusterRequest() + request = bigtable_instance_admin.ListClustersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = bigtable_instance_admin.ListClustersResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListClustersResponse(), + metadata, + ) - client.create_cluster( + client.list_clusters( request, metadata=[ ("key", "val"), @@ -20710,9 +22982,7 @@ def test_create_cluster_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_cluster_rest_bad_request( - request_type=bigtable_instance_admin.GetClusterRequest, -): +def test_update_cluster_rest_bad_request(request_type=instance.Cluster): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -20733,17 +23003,17 @@ def test_get_cluster_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_cluster(request) + client.update_cluster(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.GetClusterRequest, + instance.Cluster, dict, ], ) -def test_get_cluster_rest_call_success(request_type): +def test_update_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -20755,42 +23025,23 @@ def test_get_cluster_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = instance.Cluster( - name="name_value", - location="location_value", - state=instance.Cluster.State.READY, - serve_nodes=1181, - node_scaling_factor=instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X, - default_storage_type=common.StorageType.SSD, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = instance.Cluster.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, instance.Cluster) - assert response.name == "name_value" - assert response.location == "location_value" - assert response.state == instance.Cluster.State.READY - assert response.serve_nodes == 1181 - assert ( - response.node_scaling_factor - == instance.Cluster.NodeScalingFactor.NODE_SCALING_FACTOR_1X - ) - assert response.default_storage_type == common.StorageType.SSD + response = client.update_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): +def test_update_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20802,23 +23053,22 @@ def test_get_cluster_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_get_cluster" + transports.BigtableInstanceAdminRestInterceptor, "post_update_cluster" ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_get_cluster_with_metadata", + "post_update_cluster_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_get_cluster" + transports.BigtableInstanceAdminRestInterceptor, "pre_update_cluster" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.GetClusterRequest.pb( - bigtable_instance_admin.GetClusterRequest() - ) + pb_message = instance.Cluster.pb(instance.Cluster()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20829,19 +23079,19 @@ def test_get_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = instance.Cluster.to_json(instance.Cluster()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.GetClusterRequest() + request = instance.Cluster() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = instance.Cluster() - post_with_metadata.return_value = instance.Cluster(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_cluster( + client.update_cluster( request, metadata=[ ("key", "val"), @@ -20854,14 +23104,16 @@ def test_get_cluster_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_clusters_rest_bad_request( - request_type=bigtable_instance_admin.ListClustersRequest, +def test_partial_update_cluster_rest_bad_request( + request_type=bigtable_instance_admin.PartialUpdateClusterRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2"} + request_init = { + "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -20877,55 +23129,137 @@ def test_list_clusters_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_clusters(request) + client.partial_update_cluster(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.ListClustersRequest, + bigtable_instance_admin.PartialUpdateClusterRequest, dict, ], ) -def test_list_clusters_rest_call_success(request_type): +def test_partial_update_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/instances/sample2"} + request_init = { + "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + } + request_init["cluster"] = { + "name": "projects/sample1/instances/sample2/clusters/sample3", + "location": "location_value", + "state": 1, + "serve_nodes": 1181, + "node_scaling_factor": 1, + "cluster_config": { + "cluster_autoscaling_config": { + "autoscaling_limits": { + "min_serve_nodes": 1600, + "max_serve_nodes": 1602, + }, + "autoscaling_targets": { + "cpu_utilization_percent": 2483, + "storage_utilization_gib_per_node": 3404, + }, + } + }, + "default_storage_type": 1, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = bigtable_instance_admin.PartialUpdateClusterRequest.meta.fields[ + "cluster" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = bigtable_instance_admin.ListClustersResponse( - failed_locations=["failed_locations_value"], - next_page_token="next_page_token_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigtable_instance_admin.ListClustersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_clusters(request) - - assert response.raw_page is response + response = client.partial_update_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, bigtable_instance_admin.ListClustersResponse) - assert response.failed_locations == ["failed_locations_value"] - assert response.next_page_token == "next_page_token_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): +def test_partial_update_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20937,22 +23271,25 @@ def test_list_clusters_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_list_clusters" + transports.BigtableInstanceAdminRestInterceptor, + "post_partial_update_cluster", ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_list_clusters_with_metadata", + "post_partial_update_cluster_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_list_clusters" + transports.BigtableInstanceAdminRestInterceptor, + "pre_partial_update_cluster", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.ListClustersRequest.pb( - bigtable_instance_admin.ListClustersRequest() + pb_message = bigtable_instance_admin.PartialUpdateClusterRequest.pb( + bigtable_instance_admin.PartialUpdateClusterRequest() ) transcode.return_value = { "method": "post", @@ -20964,24 +23301,19 @@ def test_list_clusters_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = bigtable_instance_admin.ListClustersResponse.to_json( - bigtable_instance_admin.ListClustersResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.ListClustersRequest() + request = bigtable_instance_admin.PartialUpdateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = bigtable_instance_admin.ListClustersResponse() - post_with_metadata.return_value = ( - bigtable_instance_admin.ListClustersResponse(), - metadata, - ) + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_clusters( + client.partial_update_cluster( request, metadata=[ ("key", "val"), @@ -20994,7 +23326,9 @@ def test_list_clusters_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_cluster_rest_bad_request(request_type=instance.Cluster): +def test_delete_cluster_rest_bad_request( + request_type=bigtable_instance_admin.DeleteClusterRequest, +): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21015,17 +23349,17 @@ def test_update_cluster_rest_bad_request(request_type=instance.Cluster): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_cluster(request) + client.delete_cluster(request) @pytest.mark.parametrize( "request_type", [ - instance.Cluster, + bigtable_instance_admin.DeleteClusterRequest, dict, ], ) -def test_update_cluster_rest_call_success(request_type): +def test_delete_cluster_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21037,23 +23371,23 @@ def test_update_cluster_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_cluster(request) + response = client.delete_cluster(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): +def test_delete_cluster_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21065,22 +23399,14 @@ def test_update_cluster_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), - mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "post_update_cluster" - ) as post, - mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, - "post_update_cluster_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_update_cluster" + transports.BigtableInstanceAdminRestInterceptor, "pre_delete_cluster" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = instance.Cluster.pb(instance.Cluster()) + pb_message = bigtable_instance_admin.DeleteClusterRequest.pb( + bigtable_instance_admin.DeleteClusterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -21091,19 +23417,15 @@ def test_update_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - request = instance.Cluster() + request = bigtable_instance_admin.DeleteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_cluster( + client.delete_cluster( request, metadata=[ ("key", "val"), @@ -21112,19 +23434,19 @@ def test_update_cluster_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_partial_update_cluster_rest_bad_request( - request_type=bigtable_instance_admin.PartialUpdateClusterRequest, +def test_update_memory_layer_rest_bad_request( + request_type=bigtable_instance_admin.UpdateMemoryLayerRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + "memory_layer": { + "name": "projects/sample1/instances/sample2/clusters/sample3/memoryLayer" + } } request = request_type(**request_init) @@ -21141,53 +23463,40 @@ def test_partial_update_cluster_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.partial_update_cluster(request) + client.update_memory_layer(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.PartialUpdateClusterRequest, + bigtable_instance_admin.UpdateMemoryLayerRequest, dict, ], ) -def test_partial_update_cluster_rest_call_success(request_type): +def test_update_memory_layer_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "cluster": {"name": "projects/sample1/instances/sample2/clusters/sample3"} + "memory_layer": { + "name": "projects/sample1/instances/sample2/clusters/sample3/memoryLayer" + } } - request_init["cluster"] = { - "name": "projects/sample1/instances/sample2/clusters/sample3", - "location": "location_value", + request_init["memory_layer"] = { + "name": "projects/sample1/instances/sample2/clusters/sample3/memoryLayer", + "memory_config": {"storage_size_gib": 1696}, + "etag": "etag_value", "state": 1, - "serve_nodes": 1181, - "node_scaling_factor": 1, - "cluster_config": { - "cluster_autoscaling_config": { - "autoscaling_limits": { - "min_serve_nodes": 1600, - "max_serve_nodes": 1602, - }, - "autoscaling_targets": { - "cpu_utilization_percent": 2483, - "storage_utilization_gib_per_node": 3404, - }, - } - }, - "default_storage_type": 1, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = bigtable_instance_admin.PartialUpdateClusterRequest.meta.fields[ - "cluster" + test_field = bigtable_instance_admin.UpdateMemoryLayerRequest.meta.fields[ + "memory_layer" ] def get_message_fields(field): @@ -21216,7 +23525,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER + for field, value in request_init["memory_layer"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -21246,10 +23555,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] + for i in range(0, len(request_init["memory_layer"][field])): + del request_init["memory_layer"][field][i][subfield] else: - del request_init["cluster"][field][subfield] + del request_init["memory_layer"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -21264,14 +23573,14 @@ def get_message_fields(field): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.partial_update_cluster(request) + response = client.update_memory_layer(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_partial_update_cluster_rest_interceptors(null_interceptor): +def test_update_memory_layer_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21285,23 +23594,21 @@ def test_partial_update_cluster_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, - "post_partial_update_cluster", + transports.BigtableInstanceAdminRestInterceptor, "post_update_memory_layer" ) as post, mock.patch.object( transports.BigtableInstanceAdminRestInterceptor, - "post_partial_update_cluster_with_metadata", + "post_update_memory_layer_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, - "pre_partial_update_cluster", + transports.BigtableInstanceAdminRestInterceptor, "pre_update_memory_layer" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = bigtable_instance_admin.PartialUpdateClusterRequest.pb( - bigtable_instance_admin.PartialUpdateClusterRequest() + pb_message = bigtable_instance_admin.UpdateMemoryLayerRequest.pb( + bigtable_instance_admin.UpdateMemoryLayerRequest() ) transcode.return_value = { "method": "post", @@ -21316,7 +23623,7 @@ def test_partial_update_cluster_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = bigtable_instance_admin.PartialUpdateClusterRequest() + request = bigtable_instance_admin.UpdateMemoryLayerRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -21325,7 +23632,7 @@ def test_partial_update_cluster_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.partial_update_cluster( + client.update_memory_layer( request, metadata=[ ("key", "val"), @@ -21338,14 +23645,14 @@ def test_partial_update_cluster_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_cluster_rest_bad_request( - request_type=bigtable_instance_admin.DeleteClusterRequest, +def test_list_memory_layers_rest_bad_request( + request_type=bigtable_instance_admin.ListMemoryLayersRequest, ): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -21361,45 +23668,197 @@ def test_delete_cluster_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_cluster(request) + client.list_memory_layers(request) @pytest.mark.parametrize( "request_type", [ - bigtable_instance_admin.DeleteClusterRequest, + bigtable_instance_admin.ListMemoryLayersRequest, dict, ], ) -def test_delete_cluster_rest_call_success(request_type): +def test_list_memory_layers_rest_call_success(request_type): client = BigtableInstanceAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/instances/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/instances/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = bigtable_instance_admin.ListMemoryLayersResponse( + failed_locations=["failed_locations_value"], + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigtable_instance_admin.ListMemoryLayersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_memory_layers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMemoryLayersPager) + assert response.failed_locations == ["failed_locations_value"] + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_memory_layers_rest_interceptors(null_interceptor): + transport = transports.BigtableInstanceAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BigtableInstanceAdminRestInterceptor(), + ) + client = BigtableInstanceAdminClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "post_list_memory_layers" + ) as post, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_list_memory_layers_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_list_memory_layers" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.ListMemoryLayersRequest.pb( + bigtable_instance_admin.ListMemoryLayersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = bigtable_instance_admin.ListMemoryLayersResponse.to_json( + bigtable_instance_admin.ListMemoryLayersResponse() + ) + req.return_value.content = return_value + + request = bigtable_instance_admin.ListMemoryLayersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigtable_instance_admin.ListMemoryLayersResponse() + post_with_metadata.return_value = ( + bigtable_instance_admin.ListMemoryLayersResponse(), + metadata, + ) + + client.list_memory_layers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_memory_layer_rest_bad_request( + request_type=bigtable_instance_admin.GetMemoryLayerRequest, +): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/instances/sample2/clusters/sample3/memoryLayer" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_memory_layer(request) + + +@pytest.mark.parametrize( + "request_type", + [ + bigtable_instance_admin.GetMemoryLayerRequest, + dict, + ], +) +def test_get_memory_layer_rest_call_success(request_type): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/instances/sample2/clusters/sample3/memoryLayer" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.MemoryLayer( + name="name_value", + etag="etag_value", + state=instance.MemoryLayer.State.READY, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.MemoryLayer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_cluster(request) + response = client.get_memory_layer(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, instance.MemoryLayer) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.state == instance.MemoryLayer.State.READY @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): +def test_get_memory_layer_rest_interceptors(null_interceptor): transport = transports.BigtableInstanceAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21412,12 +23871,21 @@ def test_delete_cluster_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.BigtableInstanceAdminRestInterceptor, "pre_delete_cluster" + transports.BigtableInstanceAdminRestInterceptor, "post_get_memory_layer" + ) as post, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, + "post_get_memory_layer_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BigtableInstanceAdminRestInterceptor, "pre_get_memory_layer" ) as pre, ): pre.assert_not_called() - pb_message = bigtable_instance_admin.DeleteClusterRequest.pb( - bigtable_instance_admin.DeleteClusterRequest() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = bigtable_instance_admin.GetMemoryLayerRequest.pb( + bigtable_instance_admin.GetMemoryLayerRequest() ) transcode.return_value = { "method": "post", @@ -21429,15 +23897,19 @@ def test_delete_cluster_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.MemoryLayer.to_json(instance.MemoryLayer()) + req.return_value.content = return_value - request = bigtable_instance_admin.DeleteClusterRequest() + request = bigtable_instance_admin.GetMemoryLayerRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = instance.MemoryLayer() + post_with_metadata.return_value = instance.MemoryLayer(), metadata - client.delete_cluster( + client.get_memory_layer( request, metadata=[ ("key", "val"), @@ -21446,6 +23918,8 @@ def test_delete_cluster_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() def test_create_app_profile_rest_bad_request( @@ -21501,7 +23975,7 @@ def test_create_app_profile_rest_call_success(request_type): "allow_transactional_writes": True, }, "priority": 1, - "standard_isolation": {"priority": 1}, + "standard_isolation": {"priority": 1, "memory_config": {}}, "data_boost_isolation_read_only": {"compute_billing_owner": 1}, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -22004,7 +24478,7 @@ def test_update_app_profile_rest_call_success(request_type): "allow_transactional_writes": True, }, "priority": 1, - "standard_isolation": {"priority": 1}, + "standard_isolation": {"priority": 1, "memory_config": {}}, "data_boost_isolation_read_only": {"compute_billing_owner": 1}, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -24638,6 +27112,67 @@ def test_delete_cluster_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_memory_layer_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_memory_layer), "__call__" + ) as call: + client.update_memory_layer(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.UpdateMemoryLayerRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_memory_layers_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_memory_layers), "__call__" + ) as call: + client.list_memory_layers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.ListMemoryLayersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_memory_layer_empty_call_rest(): + client = BigtableInstanceAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_memory_layer), "__call__") as call: + client.get_memory_layer(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bigtable_instance_admin.GetMemoryLayerRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_app_profile_empty_call_rest(): @@ -25089,6 +27624,9 @@ def test_bigtable_instance_admin_base_transport(): "update_cluster", "partial_update_cluster", "delete_cluster", + "update_memory_layer", + "list_memory_layers", + "get_memory_layer", "create_app_profile", "get_app_profile", "list_app_profiles", @@ -25450,6 +27988,15 @@ def test_bigtable_instance_admin_client_transport_session_collision(transport_na session1 = client1.transport.delete_cluster._session session2 = client2.transport.delete_cluster._session assert session1 != session2 + session1 = client1.transport.update_memory_layer._session + session2 = client2.transport.update_memory_layer._session + assert session1 != session2 + session1 = client1.transport.list_memory_layers._session + session2 = client2.transport.list_memory_layers._session + assert session1 != session2 + session1 = client1.transport.get_memory_layer._session + session2 = client2.transport.get_memory_layer._session + assert session1 != session2 session1 = client1.transport.create_app_profile._session session2 = client2.transport.create_app_profile._session assert session1 != session2 @@ -25869,10 +28416,38 @@ def test_parse_materialized_view_path(): assert expected == actual -def test_table_path(): +def test_memory_layer_path(): project = "winkle" instance = "nautilus" - table = "scallop" + cluster = "scallop" + expected = ( + "projects/{project}/instances/{instance}/clusters/{cluster}/memoryLayer".format( + project=project, + instance=instance, + cluster=cluster, + ) + ) + actual = BigtableInstanceAdminClient.memory_layer_path(project, instance, cluster) + assert expected == actual + + +def test_parse_memory_layer_path(): + expected = { + "project": "abalone", + "instance": "squid", + "cluster": "clam", + } + path = BigtableInstanceAdminClient.memory_layer_path(**expected) + + # Check that the path construction is reversible. + actual = BigtableInstanceAdminClient.parse_memory_layer_path(path) + assert expected == actual + + +def test_table_path(): + project = "whelk" + instance = "octopus" + table = "oyster" expected = "projects/{project}/instances/{instance}/tables/{table}".format( project=project, instance=instance, @@ -25884,9 +28459,9 @@ def test_table_path(): def test_parse_table_path(): expected = { - "project": "abalone", - "instance": "squid", - "table": "clam", + "project": "nudibranch", + "instance": "cuttlefish", + "table": "mussel", } path = BigtableInstanceAdminClient.table_path(**expected) @@ -25896,7 +28471,7 @@ def test_parse_table_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -25906,7 +28481,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "nautilus", } path = BigtableInstanceAdminClient.common_billing_account_path(**expected) @@ -25916,7 +28491,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -25926,7 +28501,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "abalone", } path = BigtableInstanceAdminClient.common_folder_path(**expected) @@ -25936,7 +28511,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -25946,7 +28521,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "clam", } path = BigtableInstanceAdminClient.common_organization_path(**expected) @@ -25956,7 +28531,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -25966,7 +28541,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "octopus", } path = BigtableInstanceAdminClient.common_project_path(**expected) @@ -25976,8 +28551,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -25988,8 +28563,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "cuttlefish", + "location": "mussel", } path = BigtableInstanceAdminClient.common_location_path(**expected) diff --git a/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_data.py b/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_data.py index 322135443ff6..bc7f8202d9b3 100644 --- a/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_data.py +++ b/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_data.py @@ -13,10 +13,9 @@ # limitations under the License. -import mock import pytest -from ._testing import _make_credentials +from google.cloud.bigtable.data.row import Cell, Row TIMESTAMP_MICROS = 18738724000 # Make sure millis granularity ROW_KEY = b"row-key" @@ -24,6 +23,44 @@ QUALIFIER = b"qualifier" VALUE = b"value" TABLE_NAME = "table_name" +ROWS = [ + Row( + key=ROW_KEY, + cells=[ + Cell( + value=VALUE, + row_key=ROW_KEY, + family=FAMILY_NAME, + qualifier=QUALIFIER, + timestamp_micros=TIMESTAMP_MICROS, + ) + ], + ), + Row( + key=ROW_KEY + b"2", + cells=[ + Cell( + value=VALUE, + row_key=ROW_KEY + b"2", + family=FAMILY_NAME, + qualifier=QUALIFIER, + timestamp_micros=TIMESTAMP_MICROS, + ) + ], + ), + Row( + key=ROW_KEY + b"3", + cells=[ + Cell( + value=VALUE, + row_key=ROW_KEY + b"3", + family=FAMILY_NAME, + qualifier=QUALIFIER, + timestamp_micros=TIMESTAMP_MICROS, + ) + ], + ), +] def _make_cell(*args, **kwargs): @@ -67,6 +104,45 @@ def test_cell_from_pb_with_labels(): _cell_from_pb_test_helper(labels) +def test_cell__from_data_client_cell(): + from google.cloud.bigtable.data.row import Cell as DataCell + from google.cloud.bigtable.row_data import Cell + + data_cell = DataCell( + value=VALUE, + row_key=ROW_KEY, + family=FAMILY_NAME, + qualifier=QUALIFIER, + timestamp_micros=TIMESTAMP_MICROS, + ) + + cell = Cell._from_data_client_cell(data_cell) + + assert cell.value == VALUE + assert cell.timestamp_micros == TIMESTAMP_MICROS + assert cell.labels == [] + + +def test_cell__from_data_client_cell_with_labels(): + from google.cloud.bigtable.data.row import Cell as DataCell + from google.cloud.bigtable.row_data import Cell + + data_cell = DataCell( + value=VALUE, + row_key=ROW_KEY, + family=FAMILY_NAME, + qualifier=QUALIFIER, + timestamp_micros=TIMESTAMP_MICROS, + labels=["label1", "label2"], + ) + + cell = Cell._from_data_client_cell(data_cell) + + assert cell.value == VALUE + assert cell.timestamp_micros == TIMESTAMP_MICROS + assert cell.labels == ["label1", "label2"] + + def test_cell_constructor(): value = object() cell = _make_cell(value, TIMESTAMP_MICROS) @@ -114,6 +190,76 @@ def test_partial_row_data_constructor(): assert partial_row_data._cells == {} +def test_partial_row_data__from_data_client_row(): + from google.cloud.bigtable.data.row import Cell as DataCell + from google.cloud.bigtable.data.row import Row as DataRow + from google.cloud.bigtable.row_data import PartialRowData + + cells = [ + DataCell( + value=b"1", + row_key=ROW_KEY, + family="family1", + qualifier=b"qual1", + timestamp_micros=1, + ), + DataCell( + value=b"2", + row_key=ROW_KEY, + family="family1", + qualifier=b"qual1", + timestamp_micros=2, + ), + DataCell( + value=b"3", + row_key=ROW_KEY, + family="family1", + qualifier=b"qual2", + timestamp_micros=3, + ), + DataCell( + value=b"4", + row_key=ROW_KEY, + family="family2", + qualifier=b"qual1", + timestamp_micros=4, + ), + DataCell( + value=b"5", + row_key=ROW_KEY, + family="family2", + qualifier=b"qual2", + timestamp_micros=5, + ), + ] + + row = DataRow(ROW_KEY, cells) + partial_row_data = PartialRowData._from_data_client_row(row) + + expected_cells = { + "family1": { + b"qual1": [ + _make_cell(b"1", 1), + _make_cell(b"2", 2), + ], + b"qual2": [ + _make_cell(b"3", 3), + ], + }, + "family2": { + b"qual1": [ + _make_cell(b"4", 4), + ], + b"qual2": [ + _make_cell(b"5", 5), + ], + }, + } + + assert partial_row_data._row_key == ROW_KEY + assert partial_row_data._cells == expected_cells + + def test_partial_row_data___eq__(): row_key = object() partial_row_data1 = _make_partial_row_data(row_key) @@ -287,90 +433,6 @@ def trailing_metadata(self): return TestingException(exception) -def test__retry_read_rows_exception_miss(): - from google.api_core.exceptions import Conflict - - from google.cloud.bigtable.row_data import _retry_read_rows_exception - - exception = Conflict("testing") - assert not _retry_read_rows_exception(exception) - - -def test__retry_read_rows_exception_service_unavailable(): - from google.api_core.exceptions import ServiceUnavailable - - from google.cloud.bigtable.row_data import _retry_read_rows_exception - - exception = ServiceUnavailable("testing") - assert _retry_read_rows_exception(exception) - - -def test__retry_read_rows_exception_deadline_exceeded(): - from google.api_core.exceptions import DeadlineExceeded - - from google.cloud.bigtable.row_data import _retry_read_rows_exception - - exception = DeadlineExceeded("testing") - assert _retry_read_rows_exception(exception) - - -def test__retry_read_rows_exception_internal_server_not_retriable(): - from google.api_core.exceptions import InternalServerError - - from google.cloud.bigtable.row_data import ( - RETRYABLE_INTERNAL_ERROR_MESSAGES, - _retry_read_rows_exception, - ) - - err_message = "500 Error" - exception = InternalServerError(err_message) - assert err_message not in RETRYABLE_INTERNAL_ERROR_MESSAGES - assert not _retry_read_rows_exception(exception) - - -def test__retry_read_rows_exception_internal_server_retriable(): - from google.api_core.exceptions import InternalServerError - - from google.cloud.bigtable.row_data import ( - RETRYABLE_INTERNAL_ERROR_MESSAGES, - _retry_read_rows_exception, - ) - - for err_message in RETRYABLE_INTERNAL_ERROR_MESSAGES: - exception = InternalServerError(err_message) - assert _retry_read_rows_exception(exception) - - -def test__retry_read_rows_exception_miss_wrapped_in_grpc(): - from google.api_core.exceptions import Conflict - - from google.cloud.bigtable.row_data import _retry_read_rows_exception - - wrapped = Conflict("testing") - exception = _make_grpc_call_error(wrapped) - assert not _retry_read_rows_exception(exception) - - -def test__retry_read_rows_exception_service_unavailable_wrapped_in_grpc(): - from google.api_core.exceptions import ServiceUnavailable - - from google.cloud.bigtable.row_data import _retry_read_rows_exception - - wrapped = ServiceUnavailable("testing") - exception = _make_grpc_call_error(wrapped) - assert _retry_read_rows_exception(exception) - - -def test__retry_read_rows_exception_deadline_exceeded_wrapped_in_grpc(): - from google.api_core.exceptions import DeadlineExceeded - - from google.cloud.bigtable.row_data import _retry_read_rows_exception - - wrapped = DeadlineExceeded("testing") - exception = _make_grpc_call_error(wrapped) - assert _retry_read_rows_exception(exception) - - def test_partial_cell_data(): from google.cloud.bigtable.row_data import PartialCellData @@ -395,65 +457,32 @@ def test_partial_cell_data(): assert instance.value == added_value + added_value -def _make_partial_rows_data(*args, **kwargs): +def _make_partial_rows_data(generator): from google.cloud.bigtable.row_data import PartialRowsData - return PartialRowsData(*args, **kwargs) + return PartialRowsData._from_generator(generator) def _partial_rows_data_consume_all(yrd): return [row.row_key for row in yrd] -def _make_client(*args, **kwargs): - from google.cloud.bigtable.client import Client - - return Client(*args, **kwargs) +def _make_generator(rows, error=None): + for row in rows: + if error: + raise error + else: + yield row -def test_partial_rows_data_constructor(): - from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS - - client = _Client() - client._data_stub = mock.MagicMock() - request = object() - partial_rows_data = _make_partial_rows_data(client._data_stub.ReadRows, request) - assert partial_rows_data.request is request - assert partial_rows_data.rows == {} - assert partial_rows_data.retry == DEFAULT_RETRY_READ_ROWS +def _assert_generator_closed(generator): + with pytest.raises(StopIteration): + next(generator) def test_partial_rows_data_consume_all(): - resp = _ReadRowsResponseV2( - [ - _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ), - _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY + b"2", - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ), - ] - ) - - call_count = 0 - iterator = _MockCancellableIterator(resp) - - def fake_read(*args, **kwargs): - nonlocal call_count - call_count += 1 - return iterator - - partial_rows_data = _make_partial_rows_data(fake_read, None) + generator = _make_generator(ROWS) + partial_rows_data = _make_partial_rows_data(generator) partial_rows_data.consume_all() row1 = _make_partial_row_data(ROW_KEY) @@ -464,772 +493,125 @@ def fake_read(*args, **kwargs): row2._cells[FAMILY_NAME] = { QUALIFIER: [_make_cell(value=VALUE, timestamp_micros=TIMESTAMP_MICROS)] } + row3 = _make_partial_row_data(ROW_KEY + b"3") + row3._cells[FAMILY_NAME] = { + QUALIFIER: [_make_cell(value=VALUE, timestamp_micros=TIMESTAMP_MICROS)] + } - assert partial_rows_data.rows == {row1.row_key: row1, row2.row_key: row2} - - -def test_partial_rows_data_constructor_with_retry(): - from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS - - client = _Client() - client._data_stub = mock.MagicMock() - request = object() - retry = DEFAULT_RETRY_READ_ROWS - partial_rows_data = _make_partial_rows_data( - client._data_stub.ReadRows, request, retry - ) - partial_rows_data.read_method.assert_called_once_with( - request, - timeout=DEFAULT_RETRY_READ_ROWS.deadline + 1, - retry=DEFAULT_RETRY_READ_ROWS, - ) - assert partial_rows_data.request is request - assert partial_rows_data.rows == {} - assert partial_rows_data.retry == retry - - -def test_partial_rows_data___eq__(): - client = _Client() - client._data_stub = mock.MagicMock() - request = object() - partial_rows_data1 = _make_partial_rows_data(client._data_stub.ReadRows, request) - partial_rows_data2 = _make_partial_rows_data(client._data_stub.ReadRows, request) - assert partial_rows_data1.rows == partial_rows_data2.rows - - -def test_partial_rows_data___eq__type_differ(): - client = _Client() - client._data_stub = mock.MagicMock() - request = object() - partial_rows_data1 = _make_partial_rows_data(client._data_stub.ReadRows, request) - partial_rows_data2 = object() - assert not (partial_rows_data1 == partial_rows_data2) - - -def test_partial_rows_data___ne__same_value(): - client = _Client() - client._data_stub = mock.MagicMock() - request = object() - partial_rows_data1 = _make_partial_rows_data(client._data_stub.ReadRows, request) - partial_rows_data2 = _make_partial_rows_data(client._data_stub.ReadRows, request) - assert partial_rows_data1 != partial_rows_data2 - - -def test_partial_rows_data___ne__(): - client = _Client() - client._data_stub = mock.MagicMock() - request = object() - partial_rows_data1 = _make_partial_rows_data(client._data_stub.ReadRows, request) - partial_rows_data2 = _make_partial_rows_data(client._data_stub.ReadRows, request) - assert partial_rows_data1 != partial_rows_data2 - - -def test_partial_rows_data_rows_getter(): - client = _Client() - client._data_stub = mock.MagicMock() - request = object() - partial_rows_data = _make_partial_rows_data(client._data_stub.ReadRows, request) - partial_rows_data.rows = value = object() - assert partial_rows_data.rows is value - - -def test_partial_rows_data_state_start(): - client = _Client() - iterator = _MockCancellableIterator() - client._data_stub = mock.MagicMock() - client._data_stub.ReadRows.side_effect = [iterator] - request = object() - yrd = _make_partial_rows_data(client._data_stub.ReadRows, request) - assert yrd.state == yrd.NEW_ROW - - -def test_partial_rows_data_state_new_row_w_row(): - from google.cloud.bigtable_v2.services.bigtable import BigtableClient - - chunk = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - chunks = [chunk] - - response = _ReadRowsResponseV2(chunks) - iterator = _MockCancellableIterator(response) - - data_api = mock.create_autospec(BigtableClient) - - credentials = _make_credentials() - client = _make_client(project="project-id", credentials=credentials, admin=True) - client._table_data_client = data_api - request = object() - - yrd = _make_partial_rows_data(client._table_data_client.read_rows, request) - assert yrd.retry._deadline == 60.0 - - yrd.response_iterator = iterator - rows = [row for row in yrd] - - result = rows[0] - assert result.row_key == ROW_KEY - assert yrd._counter == 1 - assert yrd.state == yrd.NEW_ROW - - -def test_partial_rows_data_multiple_chunks(): - from google.cloud.bigtable_v2.services.bigtable import BigtableClient - - chunk1 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=False, - ) - chunk2 = _ReadRowsResponseCellChunkPB( - qualifier=QUALIFIER + b"1", - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - chunks = [chunk1, chunk2] - - response = _ReadRowsResponseV2(chunks) - iterator = _MockCancellableIterator(response) - data_api = mock.create_autospec(BigtableClient) - credentials = _make_credentials() - client = _make_client(project="project-id", credentials=credentials, admin=True) - client._table_data_client = data_api - request = object() - - yrd = _make_partial_rows_data(data_api.read_rows, request) + assert partial_rows_data.rows == { + row1.row_key: row1, + row2.row_key: row2, + row3.row_key: row3, + } - yrd.response_iterator = iterator - rows = [row for row in yrd] - result = rows[0] - assert result.row_key == ROW_KEY - assert yrd._counter == 1 - assert yrd.state == yrd.NEW_ROW + _assert_generator_closed(generator) def test_partial_rows_data_cancel(): - client = _Client() - response_iterator = _MockCancellableIterator() - client._data_stub = mock.MagicMock() - client._data_stub.ReadRows.side_effect = [response_iterator] - request = object() - yield_rows_data = _make_partial_rows_data(client._data_stub.ReadRows, request) - assert response_iterator.cancel_calls == 0 - yield_rows_data.cancel() - assert response_iterator.cancel_calls == 1 - assert list(yield_rows_data) == [] - - -def test_partial_rows_data_cancel_between_chunks(): - from google.cloud.bigtable_v2.services.bigtable import BigtableClient - - chunk1 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - chunk2 = _ReadRowsResponseCellChunkPB( - qualifier=QUALIFIER + b"1", - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - chunks = [chunk1, chunk2] - response = _ReadRowsResponseV2(chunks) - response_iterator = _MockCancellableIterator(response) - - client = _Client() - data_api = mock.create_autospec(BigtableClient) - client._table_data_client = data_api - request = object() - yrd = _make_partial_rows_data(data_api.read_rows, request) - yrd.response_iterator = response_iterator - - rows = [] - for row in yrd: - yrd.cancel() - rows.append(row) - - assert response_iterator.cancel_calls == 1 - assert list(yrd) == [] - - -def test_partial_rows_data_valid_last_scanned_row_key_on_start(): - client = _Client() - response = _ReadRowsResponseV2([], last_scanned_row_key=b"2.AFTER") - iterator = _MockCancellableIterator(response) - client._data_stub = mock.MagicMock() - client._data_stub.read_rows.side_effect = [iterator] - request = object() - yrd = _make_partial_rows_data(client._data_stub.read_rows, request) - yrd.last_scanned_row_key = b"1.BEFORE" - _partial_rows_data_consume_all(yrd) - assert yrd.last_scanned_row_key == b"2.AFTER" - - -def test_partial_rows_data_invalid_empty_chunk(): - from google.cloud.bigtable.row_data import InvalidChunk - from google.cloud.bigtable_v2.services.bigtable import BigtableClient - - client = _Client() - chunks = _generate_cell_chunks([""]) - response = _ReadRowsResponseV2(chunks) - iterator = _MockCancellableIterator(response) - client._data_stub = mock.create_autospec(BigtableClient) - client._data_stub.read_rows.side_effect = [iterator] - request = object() - yrd = _make_partial_rows_data(client._data_stub.read_rows, request) - with pytest.raises(InvalidChunk): - _partial_rows_data_consume_all(yrd) - - -def test_partial_rows_data_state_cell_in_progress(): - labels = ["L1", "L2"] - resp = _ReadRowsResponseV2( - [ - _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - value_size=(2 * len(VALUE)), - labels=labels, - ), - _ReadRowsResponseCellChunkPB(value=VALUE, commit_row=True), - ] - ) - - def fake_read(*args, **kwargs): - return iter([resp]) + generator = _make_generator(ROWS) + partial_rows_data = _make_partial_rows_data(generator) + row_data = [] - yrd = _make_partial_rows_data(fake_read, None) - yrd.consume_all() + count = 0 + for row in partial_rows_data: + row_data.append(row) + count += 1 + if count == 1: + partial_rows_data.cancel() - expected_row = _make_partial_row_data(ROW_KEY) - expected_row._cells = { - QUALIFIER: [ - _make_cell( - value=(VALUE + VALUE), timestamp_micros=TIMESTAMP_MICROS, labels=labels - ) - ] + row1 = _make_partial_row_data(ROW_KEY) + row1._cells[FAMILY_NAME] = { + QUALIFIER: [_make_cell(value=VALUE, timestamp_micros=TIMESTAMP_MICROS)] } + assert row_data == [row1] + # We should have closed the generator, so there should be no more + # elements left in there even though we haven't iterated through all the rows. + _assert_generator_closed(generator) -def test_partial_rows_data_yield_rows_data(): - from google.cloud.bigtable_v2.services.bigtable import BigtableClient - client = _Client() +def test_partial_rows_data_deadline_exceeded(): + from google.api_core import exceptions - chunk = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, + generator = _make_generator( + ROWS, error=exceptions.DeadlineExceeded("Operation timed out.") ) - chunks = [chunk] - - response = _ReadRowsResponseV2(chunks) - iterator = _MockCancellableIterator(response) - data_api = mock.create_autospec(BigtableClient) - client._data_stub = data_api - client._data_stub.read_rows.side_effect = [iterator] - - request = object() - yrd = _make_partial_rows_data(client._data_stub.read_rows, request) + partial_rows_data = _make_partial_rows_data(generator) + with pytest.raises(exceptions.RetryError): + list(partial_rows_data) - result = _partial_rows_data_consume_all(yrd)[0] + # An exception should close the generator. + _assert_generator_closed(generator) - assert result == ROW_KEY +def _make_cell_pb(value): + from google.cloud.bigtable import row_data -def test_partial_rows_data_yield_retry_rows_data(): - from google.api_core import retry + return row_data.Cell(value, TIMESTAMP_MICROS) - client = _Client() - retry_read_rows = retry.Retry(predicate=_read_rows_retry_exception) +def test_partial_rows_data_legacy_constructor_fallback(): + import warnings - chunk = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - chunks = [chunk] - - response = _ReadRowsResponseV2(chunks) - failure_iterator = _MockFailureIterator_1() - iterator = _MockCancellableIterator(response) - client._data_stub = mock.MagicMock() - client._data_stub.ReadRows.side_effect = [failure_iterator, iterator] + from google.cloud.bigtable.row_data import PartialRowsData + read_method = object() request = object() - yrd = _make_partial_rows_data(client._data_stub.ReadRows, request, retry_read_rows) - - result = _partial_rows_data_consume_all(yrd)[0] - - assert result == ROW_KEY - - -def _make_read_rows_request_manager(*args, **kwargs): - from google.cloud.bigtable.row_data import _ReadRowsRequestManager - - return _ReadRowsRequestManager(*args, **kwargs) - - -@pytest.fixture(scope="session") -def rrrm_data(): - from google.cloud.bigtable import row_set - - row_range1 = row_set.RowRange(b"row_key21", b"row_key29") - row_range2 = row_set.RowRange(b"row_key31", b"row_key39") - row_range3 = row_set.RowRange(b"row_key41", b"row_key49") - - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request.rows.row_ranges.append(row_range1.get_range_kwargs()) - request.rows.row_ranges.append(row_range2.get_range_kwargs()) - request.rows.row_ranges.append(row_range3.get_range_kwargs()) - - yield { - "row_range1": row_range1, - "row_range2": row_range2, - "row_range3": row_range3, - "request": request, - } - - -def test_RRRM_constructor(): - request = mock.Mock() - last_scanned_key = "last_key" - rows_read_so_far = 10 - - request_manager = _make_read_rows_request_manager( - request, last_scanned_key, rows_read_so_far - ) - assert request == request_manager.message - assert last_scanned_key == request_manager.last_scanned_key - assert rows_read_so_far == request_manager.rows_read_so_far - - -def test_RRRM__filter_row_key(): - table_name = "table_name" - request = _ReadRowsRequestPB(table_name=table_name) - request.rows.row_keys.extend([b"row_key1", b"row_key2", b"row_key3", b"row_key4"]) - - last_scanned_key = b"row_key2" - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - row_keys = request_manager._filter_rows_keys() - - expected_row_keys = [b"row_key3", b"row_key4"] - assert expected_row_keys == row_keys - - -def test_RRRM__filter_row_key_is_empty(): - table_name = "table_name" - request = _ReadRowsRequestPB(table_name=table_name) - request.rows.row_keys.extend([b"row_key1", b"row_key2", b"row_key3", b"row_key4"]) - - last_scanned_key = b"row_key4" - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 4) - row_keys = request_manager._filter_rows_keys() - - assert row_keys == [] - - -def test_RRRM__filter_row_ranges_all_ranges_added_back(rrrm_data): - from google.cloud.bigtable_v2.types import data as data_v2_pb2 - - request = rrrm_data["request"] - last_scanned_key = b"row_key14" - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - row_ranges = request_manager._filter_row_ranges() - - exp_row_range1 = data_v2_pb2.RowRange( - start_key_closed=b"row_key21", end_key_open=b"row_key29" - ) - exp_row_range2 = data_v2_pb2.RowRange( - start_key_closed=b"row_key31", end_key_open=b"row_key39" - ) - exp_row_range3 = data_v2_pb2.RowRange( - start_key_closed=b"row_key41", end_key_open=b"row_key49" - ) - exp_row_ranges = [exp_row_range1, exp_row_range2, exp_row_range3] - - assert exp_row_ranges == row_ranges - - -def test_RRRM__filter_row_ranges_all_ranges_already_read(rrrm_data): - request = rrrm_data["request"] - last_scanned_key = b"row_key54" - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - row_ranges = request_manager._filter_row_ranges() - - assert row_ranges == [] - - -def test_RRRM__filter_row_ranges_all_ranges_already_read_open_closed(): - from google.cloud.bigtable import row_set - - last_scanned_key = b"row_key54" - - row_range1 = row_set.RowRange(b"row_key21", b"row_key29", False, True) - row_range2 = row_set.RowRange(b"row_key31", b"row_key39") - row_range3 = row_set.RowRange(b"row_key41", b"row_key49", False, True) - - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request.rows.row_ranges.append(row_range1.get_range_kwargs()) - request.rows.row_ranges.append(row_range2.get_range_kwargs()) - request.rows.row_ranges.append(row_range3.get_range_kwargs()) - - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - request_manager.new_message = _ReadRowsRequestPB(table_name=TABLE_NAME) - row_ranges = request_manager._filter_row_ranges() - - assert row_ranges == [] - - -def test_RRRM__filter_row_ranges_some_ranges_already_read(rrrm_data): - from google.cloud.bigtable_v2.types import data as data_v2_pb2 - - request = rrrm_data["request"] - last_scanned_key = b"row_key22" - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - request_manager.new_message = _ReadRowsRequestPB(table_name=TABLE_NAME) - row_ranges = request_manager._filter_row_ranges() - - exp_row_range1 = data_v2_pb2.RowRange( - start_key_open=b"row_key22", end_key_open=b"row_key29" - ) - exp_row_range2 = data_v2_pb2.RowRange( - start_key_closed=b"row_key31", end_key_open=b"row_key39" - ) - exp_row_range3 = data_v2_pb2.RowRange( - start_key_closed=b"row_key41", end_key_open=b"row_key49" - ) - exp_row_ranges = [exp_row_range1, exp_row_range2, exp_row_range3] - - assert exp_row_ranges == row_ranges - - -def test_RRRM_build_updated_request(rrrm_data): - from google.cloud.bigtable.row_filters import RowSampleFilter - from google.cloud.bigtable_v2 import types - - row_range1 = rrrm_data["row_range1"] - row_filter = RowSampleFilter(0.33) - last_scanned_key = b"row_key25" - request = _ReadRowsRequestPB( - filter=row_filter._to_pb(), - rows_limit=8, - table_name=TABLE_NAME, - app_profile_id="app-profile-id-1", - ) - request.rows.row_ranges.append(row_range1.get_range_kwargs()) - - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - - result = request_manager.build_updated_request() - - expected_result = _ReadRowsRequestPB( - table_name=TABLE_NAME, - filter=row_filter._to_pb(), - rows_limit=6, - app_profile_id="app-profile-id-1", - ) - - row_range1 = types.RowRange( - start_key_open=last_scanned_key, end_key_open=row_range1.end_key - ) - expected_result.rows.row_ranges.append(row_range1) - - assert expected_result == result - - -def test_RRRM_build_updated_request_full_table(): - from google.cloud.bigtable_v2 import types - - last_scanned_key = b"row_key14" - - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - - result = request_manager.build_updated_request() - expected_result = _ReadRowsRequestPB(table_name=TABLE_NAME) - row_range1 = types.RowRange(start_key_open=last_scanned_key) - expected_result.rows.row_ranges.append(row_range1) - assert expected_result == result - - -def test_RRRM_build_updated_request_no_start_key(): - from google.cloud.bigtable.row_filters import RowSampleFilter - from google.cloud.bigtable_v2 import types - - row_filter = RowSampleFilter(0.33) - last_scanned_key = b"row_key25" - request = _ReadRowsRequestPB( - filter=row_filter._to_pb(), rows_limit=8, table_name=TABLE_NAME - ) - row_range1 = types.RowRange(end_key_open=b"row_key29") - request.rows.row_ranges.append(row_range1) - - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - - result = request_manager.build_updated_request() + with warnings.catch_warnings(record=True) as warned: + warnings.simplefilter("always") + prd = PartialRowsData(read_method, request) - expected_result = _ReadRowsRequestPB( - table_name=TABLE_NAME, filter=row_filter._to_pb(), rows_limit=6 + assert len(warned) == 1 + assert issubclass(warned[0].category, DeprecationWarning) + assert "Direct instantiation of `PartialRowsData` is deprecated" in str( + warned[0].message ) - - row_range2 = types.RowRange( - start_key_open=last_scanned_key, end_key_open=b"row_key29" - ) - expected_result.rows.row_ranges.append(row_range2) - - assert expected_result == result - - -def test_RRRM_build_updated_request_no_end_key(): - from google.cloud.bigtable.row_filters import RowSampleFilter - from google.cloud.bigtable_v2 import types - - row_filter = RowSampleFilter(0.33) - last_scanned_key = b"row_key25" - request = _ReadRowsRequestPB( - filter=row_filter._to_pb(), rows_limit=8, table_name=TABLE_NAME - ) - - row_range1 = types.RowRange(start_key_closed=b"row_key20") - request.rows.row_ranges.append(row_range1) - - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - - result = request_manager.build_updated_request() - - expected_result = _ReadRowsRequestPB( - table_name=TABLE_NAME, filter=row_filter._to_pb(), rows_limit=6 - ) - row_range2 = types.RowRange(start_key_open=last_scanned_key) - expected_result.rows.row_ranges.append(row_range2) - - assert expected_result == result - - -def test_RRRM_build_updated_request_rows(): - from google.cloud.bigtable.row_filters import RowSampleFilter - - row_filter = RowSampleFilter(0.33) - last_scanned_key = b"row_key4" - request = _ReadRowsRequestPB( - filter=row_filter._to_pb(), rows_limit=5, table_name=TABLE_NAME - ) - request.rows.row_keys.extend( - [b"row_key1", b"row_key2", b"row_key4", b"row_key5", b"row_key7", b"row_key9"] - ) - - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 3) - - result = request_manager.build_updated_request() - - expected_result = _ReadRowsRequestPB( - table_name=TABLE_NAME, filter=row_filter._to_pb(), rows_limit=2 - ) - expected_result.rows.row_keys.extend([b"row_key5", b"row_key7", b"row_key9"]) - - assert expected_result == result + assert list(prd) == [] + assert prd.rows == {} + # cancel() should work cleanly on the generator fallback + prd.cancel() -def test_RRRM_build_updated_request_rows_limit(): - from google.cloud.bigtable_v2 import types +def test_partial_rows_data_keyword_generator(): + import warnings - last_scanned_key = b"row_key14" - - request = _ReadRowsRequestPB(table_name=TABLE_NAME, rows_limit=10) - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - - result = request_manager.build_updated_request() - expected_result = _ReadRowsRequestPB(table_name=TABLE_NAME, rows_limit=8) - row_range1 = types.RowRange(start_key_open=last_scanned_key) - expected_result.rows.row_ranges.append(row_range1) - assert expected_result == result - - -def test_RRRM__key_already_read(): - last_scanned_key = b"row_key14" - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request_manager = _make_read_rows_request_manager(request, last_scanned_key, 2) - - assert request_manager._key_already_read(b"row_key11") - assert not request_manager._key_already_read(b"row_key16") - - -def test_RRRM__rows_limit_reached(): - from google.cloud.bigtable.row_data import InvalidRetryRequest - - last_scanned_key = b"row_key14" - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request.rows_limit = 2 - request_manager = _make_read_rows_request_manager( - request, last_scanned_key=last_scanned_key, rows_read_so_far=2 - ) - with pytest.raises(InvalidRetryRequest): - request_manager.build_updated_request() - - -def test_RRRM_build_updated_request_last_row_read_raises_invalid_retry_request(): - from google.cloud.bigtable.row_data import InvalidRetryRequest - - last_scanned_key = b"row_key4" - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request.rows.row_keys.extend([b"row_key1", b"row_key2", b"row_key4"]) - - request_manager = _make_read_rows_request_manager( - request, last_scanned_key, rows_read_so_far=3 - ) - with pytest.raises(InvalidRetryRequest): - request_manager.build_updated_request() - - -def test_RRRM_build_updated_request_row_ranges_read_raises_invalid_retry_request(): - from google.cloud.bigtable import row_set - from google.cloud.bigtable.row_data import InvalidRetryRequest - - row_range1 = row_set.RowRange(b"row_key21", b"row_key29") - - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request.rows.row_ranges.append(row_range1.get_range_kwargs()) - - last_scanned_key = b"row_key4" - request = _ReadRowsRequestPB( - table_name=TABLE_NAME, - ) - request.rows.row_ranges.append(row_range1.get_range_kwargs()) - - request_manager = _make_read_rows_request_manager( - request, last_scanned_key, rows_read_so_far=2 - ) - with pytest.raises(InvalidRetryRequest): - request_manager.build_updated_request() - - -def test_RRRM_build_updated_request_row_ranges_valid(): - from google.cloud.bigtable import row_set - - row_range1 = row_set.RowRange(b"row_key21", b"row_key29") - - request = _ReadRowsRequestPB(table_name=TABLE_NAME) - request.rows.row_ranges.append(row_range1.get_range_kwargs()) - - last_scanned_key = b"row_key21" - request = _ReadRowsRequestPB( - table_name=TABLE_NAME, - ) - request.rows.row_ranges.append(row_range1.get_range_kwargs()) - - request_manager = _make_read_rows_request_manager( - request, last_scanned_key, rows_read_so_far=1 - ) - updated_request = request_manager.build_updated_request() - assert len(updated_request.rows.row_ranges) > 0 - - -class _MockCancellableIterator(object): - cancel_calls = 0 - - def __init__(self, *values): - self.iter_values = iter(values) - self.last_scanned_row_key = "" - - def cancel(self): - self.cancel_calls += 1 - - def next(self): - return next(self.iter_values) - - __next__ = next - - -class _MockFailureIterator_1(object): - def next(self): - from google.api_core.exceptions import DeadlineExceeded - - raise DeadlineExceeded("Failed to read from server") - - __next__ = next - - -def _ReadRowsResponseV2(chunks, last_scanned_row_key=b""): - from google.cloud.bigtable_v2.types import bigtable as messages_v2_pb2 - - return messages_v2_pb2.ReadRowsResponse( - chunks=chunks, last_scanned_row_key=last_scanned_row_key - ) - - -def _generate_cell_chunks(chunk_text_pbs): - from google.protobuf.text_format import Merge - - from google.cloud.bigtable_v2.types.bigtable import ReadRowsResponse - - chunks = [] - - for chunk_text_pb in chunk_text_pbs: - chunk = ReadRowsResponse.CellChunk() - chunk._pb = Merge(chunk_text_pb, chunk._pb) - chunks.append(chunk) - - return chunks - - -def _ReadRowsResponseCellChunkPB(*args, **kw): - from google.cloud.bigtable_v2.types import bigtable as messages_v2_pb2 - - family_name = kw.pop("family_name", None) - qualifier = kw.pop("qualifier", None) - message = messages_v2_pb2.ReadRowsResponse.CellChunk(*args, **kw) - - if family_name: - message.family_name = family_name - if qualifier: - message.qualifier = qualifier - - return message - - -def _make_cell_pb(value): - from google.cloud.bigtable import row_data - - return row_data.Cell(value, TIMESTAMP_MICROS) - - -def _ReadRowsRequestPB(*args, **kw): - from google.cloud.bigtable_v2.types import bigtable as messages_v2_pb2 + from google.cloud.bigtable.row_data import PartialRowsData - return messages_v2_pb2.ReadRowsRequest(*args, **kw) + generator = _make_generator([]) + with warnings.catch_warnings(record=True) as warned: + warnings.simplefilter("always") + prd = PartialRowsData(generator=generator) + assert len(warned) == 0 + assert prd._generator is generator + assert prd.rows == {} -def _read_rows_retry_exception(exc): - from google.api_core.exceptions import DeadlineExceeded - return isinstance(exc, DeadlineExceeded) +def test_partial_rows_data_deprecated_properties(): + import warnings + from google.cloud.bigtable.row_data import PartialRowsData -class _Client(object): - data_stub = None + generator = _make_generator([]) + prd = PartialRowsData._from_generator(generator) + + for attr in [ + "state", + "last_scanned_row_key", + "read_method", + "request", + "retry", + "response_iterator", + ]: + with warnings.catch_warnings(record=True) as warned: + warnings.simplefilter("always") + val = getattr(prd, attr) + + assert val is None + assert len(warned) == 1 + assert issubclass(warned[0].category, DeprecationWarning) + assert f"The `{attr}` attribute on `PartialRowsData` is deprecated" in str( + warned[0].message + ) diff --git a/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_merger.py b/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_merger.py index cc9df9c70822..deac16a7f8fc 100644 --- a/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_merger.py +++ b/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_merger.py @@ -1,12 +1,8 @@ import os -from itertools import zip_longest -from typing import List import proto -import pytest -from google.cloud.bigtable.row_data import InvalidChunk, PartialRowData, PartialRowsData -from google.cloud.bigtable.row_merger import _RowMerger +from google.cloud.bigtable.row_data import PartialRowData from google.cloud.bigtable_v2.types.bigtable import ReadRowsResponse @@ -59,172 +55,3 @@ def extract_results_from_row(row: PartialRowData): ) ) return results - - -@pytest.mark.parametrize( - "test_case", parse_readrows_acceptance_tests(), ids=lambda t: t.description -) -def test_scenario(test_case: ReadRowsTest): - def fake_read(*args, **kwargs): - return iter([ReadRowsResponse(chunks=test_case.chunks)]) - - actual_results: List[ReadRowsTest.Result] = [] - try: - for row in PartialRowsData(fake_read, request=None): - actual_results.extend(extract_results_from_row(row)) - except (InvalidChunk, ValueError): - actual_results.append(ReadRowsTest.Result(error=True)) - - for expected, actual in zip_longest(test_case.results, actual_results): - assert actual == expected - - -def test_out_of_order_rows(): - row_merger = _RowMerger(last_seen_row=b"z") - with pytest.raises(InvalidChunk): - list(row_merger.process_chunks(ReadRowsResponse(last_scanned_row_key=b"a"))) - - -def test_bare_reset(): - first_chunk = ReadRowsResponse.CellChunk( - ReadRowsResponse.CellChunk( - row_key=b"a", family_name="f", qualifier=b"q", value=b"v" - ) - ) - with pytest.raises(InvalidChunk): - _process_chunks( - first_chunk, - ReadRowsResponse.CellChunk( - ReadRowsResponse.CellChunk(reset_row=True, row_key=b"a") - ), - ) - with pytest.raises(InvalidChunk): - _process_chunks( - first_chunk, - ReadRowsResponse.CellChunk( - ReadRowsResponse.CellChunk(reset_row=True, family_name="f") - ), - ) - with pytest.raises(InvalidChunk): - _process_chunks( - first_chunk, - ReadRowsResponse.CellChunk( - ReadRowsResponse.CellChunk(reset_row=True, qualifier=b"q") - ), - ) - with pytest.raises(InvalidChunk): - _process_chunks( - first_chunk, - ReadRowsResponse.CellChunk( - ReadRowsResponse.CellChunk(reset_row=True, timestamp_micros=1000) - ), - ) - with pytest.raises(InvalidChunk): - _process_chunks( - first_chunk, - ReadRowsResponse.CellChunk( - ReadRowsResponse.CellChunk(reset_row=True, labels=["a"]) - ), - ) - with pytest.raises(InvalidChunk): - _process_chunks( - first_chunk, - ReadRowsResponse.CellChunk( - ReadRowsResponse.CellChunk(reset_row=True, value=b"v") - ), - ) - - -def test_missing_family(): - with pytest.raises(InvalidChunk): - _process_chunks( - ReadRowsResponse.CellChunk( - row_key=b"a", - qualifier=b"q", - timestamp_micros=1000, - value=b"v", - commit_row=True, - ) - ) - - -def test_mid_cell_row_key_change(): - with pytest.raises(InvalidChunk): - _process_chunks( - ReadRowsResponse.CellChunk( - row_key=b"a", - family_name="f", - qualifier=b"q", - timestamp_micros=1000, - value_size=2, - value=b"v", - ), - ReadRowsResponse.CellChunk(row_key=b"b", value=b"v", commit_row=True), - ) - - -def test_mid_cell_family_change(): - with pytest.raises(InvalidChunk): - _process_chunks( - ReadRowsResponse.CellChunk( - row_key=b"a", - family_name="f", - qualifier=b"q", - timestamp_micros=1000, - value_size=2, - value=b"v", - ), - ReadRowsResponse.CellChunk(family_name="f2", value=b"v", commit_row=True), - ) - - -def test_mid_cell_qualifier_change(): - with pytest.raises(InvalidChunk): - _process_chunks( - ReadRowsResponse.CellChunk( - row_key=b"a", - family_name="f", - qualifier=b"q", - timestamp_micros=1000, - value_size=2, - value=b"v", - ), - ReadRowsResponse.CellChunk(qualifier=b"q2", value=b"v", commit_row=True), - ) - - -def test_mid_cell_timestamp_change(): - with pytest.raises(InvalidChunk): - _process_chunks( - ReadRowsResponse.CellChunk( - row_key=b"a", - family_name="f", - qualifier=b"q", - timestamp_micros=1000, - value_size=2, - value=b"v", - ), - ReadRowsResponse.CellChunk( - timestamp_micros=2000, value=b"v", commit_row=True - ), - ) - - -def test_mid_cell_labels_change(): - with pytest.raises(InvalidChunk): - _process_chunks( - ReadRowsResponse.CellChunk( - row_key=b"a", - family_name="f", - qualifier=b"q", - timestamp_micros=1000, - value_size=2, - value=b"v", - ), - ReadRowsResponse.CellChunk(labels=["b"], value=b"v", commit_row=True), - ) - - -def _process_chunks(*chunks): - req = ReadRowsResponse.pb(ReadRowsResponse(chunks=chunks)) - return list(_RowMerger().process_chunks(req)) diff --git a/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_set.py b/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_set.py index 4142348ee195..e76d1f15135c 100644 --- a/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_set.py +++ b/packages/google-cloud-bigtable/tests/unit/v2_client/test_row_set.py @@ -48,38 +48,6 @@ def test_row_set__eq__type_differ(): assert not (row_set1 == row_set2) -def test_row_set__eq__len_row_keys_differ(): - from google.cloud.bigtable.row_set import RowSet - - row_key1 = b"row_key1" - row_key2 = b"row_key1" - - row_set1 = RowSet() - row_set2 = RowSet() - - row_set1.add_row_key(row_key1) - row_set1.add_row_key(row_key2) - row_set2.add_row_key(row_key2) - - assert not (row_set1 == row_set2) - - -def test_row_set__eq__len_row_ranges_differ(): - from google.cloud.bigtable.row_set import RowRange, RowSet - - row_range1 = RowRange(b"row_key4", b"row_key9") - row_range2 = RowRange(b"row_key4", b"row_key9") - - row_set1 = RowSet() - row_set2 = RowSet() - - row_set1.add_row_range(row_range1) - row_set1.add_row_range(row_range2) - row_set2.add_row_range(row_range2) - - assert not (row_set1 == row_set2) - - def test_row_set__eq__row_keys_differ(): from google.cloud.bigtable.row_set import RowSet @@ -195,36 +163,14 @@ def test_row_set_add_row_range_with_prefix(): assert row_set.row_ranges[0].end_key == b"rox" -def test_row_set__update_message_request(): - from google.cloud._helpers import _to_bytes - - from google.cloud.bigtable.row_set import RowRange, RowSet - - row_set = RowSet() - table_name = "table_name" - row_set.add_row_key("row_key1") - row_range1 = RowRange(b"row_key21", b"row_key29") - row_set.add_row_range(row_range1) - - request = _ReadRowsRequestPB(table_name=table_name) - row_set._update_message_request(request) - - expected_request = _ReadRowsRequestPB(table_name=table_name) - expected_request.rows.row_keys.append(_to_bytes("row_key1")) - - expected_request.rows.row_ranges.append(row_range1.get_range_kwargs()) - - assert request == expected_request - - def test_row_range_constructor(): from google.cloud.bigtable.row_set import RowRange start_key = "row_key1" end_key = "row_key9" row_range = RowRange(start_key, end_key) - assert start_key == row_range.start_key - assert end_key == row_range.end_key + assert start_key == row_range.start_key.decode() + assert end_key == row_range.end_key.decode() assert row_range.start_inclusive assert not row_range.end_inclusive @@ -311,6 +257,68 @@ def test_row_range_get_range_kwargs_open_closed(): assert expected_result == actual_result +def test_row_range_get_range_kwargs_unbounded_start(): + from google.cloud.bigtable.row_set import RowRange + + end_key = b"row_key9" + expected_result = {"end_key_open": end_key} + row_range = RowRange(None, end_key) + actual_result = row_range.get_range_kwargs() + assert expected_result == actual_result + + +def test_row_range_get_range_kwargs_unbounded_end(): + from google.cloud.bigtable.row_set import RowRange + + start_key = b"row_key1" + expected_result = {"start_key_closed": start_key} + row_range = RowRange(start_key, None) + actual_result = row_range.get_range_kwargs() + assert expected_result == actual_result + + +def test_mappable_attributes_mixin_guard_recursion(): + import pytest + + from google.cloud.bigtable.helpers import _MappableAttributesMixin + + class Uninitialized(_MappableAttributesMixin): + pass + + obj = Uninitialized() + with pytest.raises(AttributeError): + _ = obj._attribute_map + with pytest.raises(AttributeError): + _ = obj.non_existent_attribute + + # Verify setattr on _attribute_map doesn't cause recursion + obj._attribute_map = {"old_attr": "new_attr"} + assert obj._attribute_map == {"old_attr": "new_attr"} + + +def test_mappable_attributes_mixin_remap(): + import pytest + + from google.cloud.bigtable.helpers import _MappableAttributesMixin + + class DummyBase: + def __init__(self, target_attr=None): + self.target_attr = target_attr + + class MappedClass(_MappableAttributesMixin, DummyBase): + _attribute_map = {"source_attr": "target_attr"} + + instance = MappedClass(source_attr="hello") + assert instance.target_attr == "hello" + assert instance.source_attr == "hello" + + instance.source_attr = "world" + assert instance.target_attr == "world" + + with pytest.raises(AttributeError): + _ = instance.unknown_attr + + def _ReadRowsRequestPB(*args, **kw): from google.cloud.bigtable_v2.types import bigtable as messages_v2_pb2 diff --git a/packages/google-cloud-bigtable/tests/unit/v2_client/test_table.py b/packages/google-cloud-bigtable/tests/unit/v2_client/test_table.py index a163f0a2a341..3a585216342d 100644 --- a/packages/google-cloud-bigtable/tests/unit/v2_client/test_table.py +++ b/packages/google-cloud-bigtable/tests/unit/v2_client/test_table.py @@ -20,6 +20,7 @@ from google.api_core.exceptions import DeadlineExceeded from grpc import StatusCode +from google.cloud.bigtable.data.read_rows_query import ReadRowsQuery from google.cloud.bigtable.row import DirectRow from ._testing import _make_credentials @@ -587,135 +588,6 @@ def _make_gapic_api(client): return gapic_client_mock -def _table_read_row_helper(chunks, expected_result, app_profile_id=None): - from google.cloud._testing import _Monkey - - from google.cloud.bigtable import table as MUT - from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS - from google.cloud.bigtable.row_filters import RowSampleFilter - from google.cloud.bigtable.row_set import RowSet - - credentials = _make_credentials() - client = _make_client(project="project-id", credentials=credentials, admin=True) - instance = client.instance(instance_id=INSTANCE_ID) - table = _make_table(TABLE_ID, instance, app_profile_id=app_profile_id) - - # Create request_pb - request_pb = object() # Returned by our mock. - mock_created = [] - - def mock_create_row_request(table_name, **kwargs): - mock_created.append((table_name, kwargs)) - return request_pb - - # Create response_iterator - if chunks is None: - response_iterator = iter(()) # no responses at all - else: - response_pb = _ReadRowsResponsePB(chunks=chunks) - response_iterator = iter([response_pb]) - - gapic_api = _make_gapic_api(client) - gapic_api.read_rows.return_value = response_iterator - - filter_obj = RowSampleFilter(0.33) - - with _Monkey(MUT, _create_row_request=mock_create_row_request): - result = table.read_row(ROW_KEY, filter_=filter_obj) - - row_set = RowSet() - row_set.add_row_key(ROW_KEY) - expected_request = [ - ( - table.name, - { - "end_inclusive": False, - "row_set": row_set, - "app_profile_id": app_profile_id, - "end_key": None, - "limit": None, - "start_key": None, - "filter_": filter_obj, - }, - ) - ] - assert result == expected_result - assert mock_created == expected_request - - gapic_api.read_rows.assert_called_once_with( - request_pb, timeout=61.0, retry=DEFAULT_RETRY_READ_ROWS - ) - - -def test_table_read_row_miss_no__responses(): - _table_read_row_helper(None, None) - - -def test_table_read_row_miss_no_chunks_in_response(): - chunks = [] - _table_read_row_helper(chunks, None) - - -def test_table_read_row_complete(): - from google.cloud.bigtable.row_data import Cell, PartialRowData - - app_profile_id = "app-profile-id" - chunk = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - chunks = [chunk] - expected_result = PartialRowData(row_key=ROW_KEY) - family = expected_result._cells.setdefault(FAMILY_NAME, {}) - column = family.setdefault(QUALIFIER, []) - column.append(Cell.from_pb(chunk)) - - _table_read_row_helper(chunks, expected_result, app_profile_id) - - -def test_table_read_row_more_than_one_row_returned(): - app_profile_id = "app-profile-id" - chunk_1 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - )._pb - chunk_2 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_2, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - )._pb - - chunks = [chunk_1, chunk_2] - - with pytest.raises(ValueError): - _table_read_row_helper(chunks, None, app_profile_id) - - -def test_table_read_row_still_partial(): - chunk = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - ) - chunks = [chunk] # No "commit row". - - with pytest.raises(ValueError): - _table_read_row_helper(chunks, None) - - _DEFAULT_SENTINEL = object() @@ -963,38 +835,60 @@ def test_table_mutate_rows_w_mutation_timeout_and_timeout_arg(): def test_table_read_rows(): - from google.cloud._testing import _Monkey - - from google.cloud.bigtable import table as MUT + from google.cloud.bigtable.data._helpers import TABLE_DEFAULT + from google.cloud.bigtable.data.read_rows_query import ReadRowsQuery + from google.cloud.bigtable.data.row import Cell, Row + from google.cloud.bigtable.row import Cell as PartialRowDataCell + from google.cloud.bigtable.row import PartialRowData from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS, PartialRowsData + from google.cloud.bigtable.row_set import RowRange credentials = _make_credentials() client = _make_client(project="project-id", credentials=credentials, admin=True) - gapic_api = _make_gapic_api(client) instance = client.instance(instance_id=INSTANCE_ID) app_profile_id = "app-profile-id" table = _make_table(TABLE_ID, instance, app_profile_id=app_profile_id) - # Create request_pb - request_pb = object() # Returned by our mock. - retry = DEFAULT_RETRY_READ_ROWS - mock_created = [] - - def mock_create_row_request(table_name, **kwargs): - mock_created.append((table_name, kwargs)) - return request_pb + # Create read_rows return value + rows = [ + Row( + key=ROW_KEY, + cells=[ + Cell( + value=VALUE, + row_key=ROW_KEY, + family=FAMILY_NAME, + qualifier=QUALIFIER, + timestamp_micros=TIMESTAMP_MICROS, + ) + ], + ), + Row( + key=ROW_KEY_1, + cells=[ + Cell( + value=VALUE, + row_key=ROW_KEY_1, + family=FAMILY_NAME, + qualifier=QUALIFIER, + timestamp_micros=TIMESTAMP_MICROS, + ) + ], + ), + ] + generator = (r for r in rows) - # Create expected_result. - expected_result = PartialRowsData( - client._table_data_client._gapic_client.transport.read_rows, request_pb, retry - ) + # Create expected result. + expected_result = PartialRowsData._from_generator(generator) # Perform the method and check the result. - start_key = b"start-key" + start_key = b"begin-key" end_key = b"end-key" filter_obj = object() limit = 22 - with _Monkey(MUT, _create_row_request=mock_create_row_request): + retry = DEFAULT_RETRY_READ_ROWS + with mock.patch.object(table._table_impl, "read_rows_stream") as read_rows_mock: + read_rows_mock.return_value = generator result = table.read_rows( start_key=start_key, end_key=end_key, @@ -1004,264 +898,42 @@ def mock_create_row_request(table_name, **kwargs): ) assert result.rows == expected_result.rows - assert result.retry == expected_result.retry - created_kwargs = { - "start_key": start_key, - "end_key": end_key, - "filter_": filter_obj, - "limit": limit, - "end_inclusive": False, - "app_profile_id": app_profile_id, - "row_set": None, - } - assert mock_created == [(table.name, created_kwargs)] - - gapic_api.read_rows.assert_called_once_with(request_pb, timeout=61.0, retry=retry) - - -def test_table_read_retry_rows(): - from google.api_core import retry - - credentials = _make_credentials() - client = _make_client(project="project-id", credentials=credentials, admin=True) - gapic_api = _make_gapic_api(client) - instance = client.instance(instance_id=INSTANCE_ID) - table = _make_table(TABLE_ID, instance) - - retry_read_rows = retry.Retry(predicate=_read_rows_retry_exception) - - # Create response_iterator - chunk_1 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_1, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - - chunk_2 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_2, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - - response_1 = _ReadRowsResponseV2([chunk_1]) - response_2 = _ReadRowsResponseV2([chunk_2]) - response_failure_iterator_1 = _MockFailureIterator_1() - response_failure_iterator_2 = _MockFailureIterator_2([response_1]) - response_iterator = _MockReadRowsIterator(response_2) - - gapic_api.table_path.return_value = ( - f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/tables/{TABLE_ID}" - ) - - gapic_api.read_rows.side_effect = [ - response_failure_iterator_1, - response_failure_iterator_2, - response_iterator, - ] - - rows = [ - row - for row in table.read_rows( - start_key=ROW_KEY_1, end_key=ROW_KEY_2, retry=retry_read_rows - ) - ] - - result = rows[1] - assert result.row_key == ROW_KEY_2 - - assert len(gapic_api.read_rows.mock_calls) == 3 - - -def test_table_read_retry_rows_no_full_table_scan(): - from google.api_core import retry - - credentials = _make_credentials() - client = _make_client(project="project-id", credentials=credentials, admin=True) - gapic_api = _make_gapic_api(client) - instance = client.instance(instance_id=INSTANCE_ID) - table = _make_table(TABLE_ID, instance) - - retry_read_rows = retry.Retry(predicate=_read_rows_retry_exception) - - # Create response_iterator - chunk_1 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_2, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - - response_1 = _ReadRowsResponseV2([chunk_1]) - response_failure_iterator_2 = _MockFailureIterator_2([response_1]) - - gapic_api.table_path.return_value = ( - f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/tables/{TABLE_ID}" - ) - - gapic_api.read_rows.side_effect = [ - response_failure_iterator_2, - ] - - rows = [ - row - for row in table.read_rows( - start_key="doesn't matter", end_key=ROW_KEY_2, retry=retry_read_rows - ) - ] - assert len(rows) == 1 - result = rows[0] - assert result.row_key == ROW_KEY_2 - - assert len(gapic_api.read_rows.mock_calls) == 1 - assert ( - len(gapic_api.read_rows.mock_calls[0].args[0].rows.row_ranges) > 0 - ) # not empty row_ranges - - -def test_table_yield_retry_rows(): - from google.cloud.bigtable.table import _create_row_request - - credentials = _make_credentials() - client = _make_client(project="project-id", credentials=credentials, admin=True) - instance = client.instance(instance_id=INSTANCE_ID) - table = _make_table(TABLE_ID, instance) - - # Create response_iterator - chunk_1 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_1, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - - chunk_2 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_2, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - - response_1 = _ReadRowsResponseV2([chunk_1]) - response_2 = _ReadRowsResponseV2([chunk_2]) - response_failure_iterator_1 = _MockFailureIterator_1() - response_failure_iterator_2 = _MockFailureIterator_2([response_1]) - response_iterator = _MockReadRowsIterator(response_2) - - gapic_api = _make_gapic_api(client) - gapic_api.table_path.return_value = ( - f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/tables/{TABLE_ID}" - ) - gapic_api.read_rows.side_effect = [ - response_failure_iterator_1, - response_failure_iterator_2, - response_iterator, - ] - - rows = [] - with warnings.catch_warnings(record=True) as warned: - for row in table.yield_rows(start_key=ROW_KEY_1, end_key=ROW_KEY_2): - rows.append(row) - - assert len(warned) >= 1 - assert DeprecationWarning in [w.category for w in warned] - - result = rows[1] - assert result.row_key == ROW_KEY_2 - - expected_request = _create_row_request( - table.name, - start_key=ROW_KEY_1, - end_key=ROW_KEY_2, - ) - gapic_api.read_rows.mock_calls = [expected_request] * 3 - - -def test_table_yield_rows_with_row_set(): - from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS - from google.cloud.bigtable.row_set import RowRange, RowSet - from google.cloud.bigtable.table import _create_row_request - - credentials = _make_credentials() - client = _make_client(project="project-id", credentials=credentials, admin=True) - instance = client.instance(instance_id=INSTANCE_ID) - table = _make_table(TABLE_ID, instance) + assert result._generator == expected_result._generator - # Create response_iterator - chunk_1 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_1, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, + expected_read_rows_query = ReadRowsQuery( + row_ranges=RowRange(start_key=start_key, end_key=end_key), + row_filter=filter_obj, + limit=limit, ) - chunk_2 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_2, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - - chunk_3 = _ReadRowsResponseCellChunkPB( - row_key=ROW_KEY_3, - family_name=FAMILY_NAME, - qualifier=QUALIFIER, - timestamp_micros=TIMESTAMP_MICROS, - value=VALUE, - commit_row=True, - ) - - response_1 = _ReadRowsResponseV2([chunk_1]) - response_2 = _ReadRowsResponseV2([chunk_2]) - response_3 = _ReadRowsResponseV2([chunk_3]) - response_iterator = _MockReadRowsIterator(response_1, response_2, response_3) - - gapic_api = _make_gapic_api(client) - gapic_api.table_path.return_value = ( - f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/tables/{TABLE_ID}" + read_rows_mock.assert_called_once_with( + expected_read_rows_query, + operation_timeout=TABLE_DEFAULT.READ_ROWS, + attempt_timeout=retry.deadline, + retryable_errors=TABLE_DEFAULT.READ_ROWS, ) - gapic_api.read_rows.side_effect = [response_iterator] - - rows = [] - row_set = RowSet() - row_set.add_row_range(RowRange(start_key=ROW_KEY_1, end_key=ROW_KEY_2)) - row_set.add_row_key(ROW_KEY_3) - - with warnings.catch_warnings(record=True) as warned: - for row in table.yield_rows(row_set=row_set): - rows.append(row) - - assert len(warned) >= 1 - assert DeprecationWarning in [w.category for w in warned] - assert rows[0].row_key == ROW_KEY_1 - assert rows[1].row_key == ROW_KEY_2 - assert rows[2].row_key == ROW_KEY_3 + # Test that the correct rows get returned. + partial_row_data = PartialRowData(ROW_KEY) + partial_row_data._cells = { + FAMILY_NAME: { + QUALIFIER: [ + PartialRowDataCell(value=VALUE, timestamp_micros=TIMESTAMP_MICROS), + ], + }, + } + partial_row_data_1 = PartialRowData(ROW_KEY_1) + partial_row_data_1._cells = { + FAMILY_NAME: { + QUALIFIER: [ + PartialRowDataCell(value=VALUE, timestamp_micros=TIMESTAMP_MICROS), + ], + }, + } + expected_row_data = [partial_row_data, partial_row_data_1] - expected_request = _create_row_request( - table.name, - start_key=ROW_KEY_1, - end_key=ROW_KEY_2, - ) - expected_request.rows.row_keys.append(ROW_KEY_3) - gapic_api.read_rows.assert_called_once_with( - expected_request, timeout=61.0, retry=DEFAULT_RETRY_READ_ROWS - ) + row_data = list(result) + assert row_data == expected_row_data def test_table_sample_row_keys(): @@ -1619,15 +1291,6 @@ def test_table_restore_table_w_backup_name(): _table_restore_helper(backup_name=BACKUP_NAME) -def test__create_row_request_table_name_only(): - from google.cloud.bigtable.table import _create_row_request - - table_name = "table_name" - result = _create_row_request(table_name) - expected_result = _ReadRowsRequestPB(table_name=table_name) - assert result == expected_result - - def test__create_row_request_row_range_row_set_conflict(): from google.cloud.bigtable.table import _create_row_request @@ -1639,12 +1302,9 @@ def test__create_row_request_row_range_start_key(): from google.cloud.bigtable.table import _create_row_request from google.cloud.bigtable_v2.types import RowRange - table_name = "table_name" - start_key = b"start_key" - result = _create_row_request(table_name, start_key=start_key) - expected_result = _ReadRowsRequestPB(table_name=table_name) - row_range = RowRange(start_key_closed=start_key) - expected_result.rows.row_ranges.append(row_range) + start_key = b"begin_key" + result = _create_row_request(start_key=start_key) + expected_result = ReadRowsQuery(row_ranges=RowRange(start_key_closed=start_key)) assert result == expected_result @@ -1652,12 +1312,9 @@ def test__create_row_request_row_range_end_key(): from google.cloud.bigtable.table import _create_row_request from google.cloud.bigtable_v2.types import RowRange - table_name = "table_name" - end_key = b"end_key" - result = _create_row_request(table_name, end_key=end_key) - expected_result = _ReadRowsRequestPB(table_name=table_name) - row_range = RowRange(end_key_open=end_key) - expected_result.rows.row_ranges.append(row_range) + end_key = b"begin_key" + result = _create_row_request(end_key=end_key) + expected_result = ReadRowsQuery(row_ranges=RowRange(end_key_open=end_key)) assert result == expected_result @@ -1665,13 +1322,12 @@ def test__create_row_request_row_range_both_keys(): from google.cloud.bigtable.table import _create_row_request from google.cloud.bigtable_v2.types import RowRange - table_name = "table_name" - start_key = b"start_key" + start_key = b"begin_key" end_key = b"end_key" - result = _create_row_request(table_name, start_key=start_key, end_key=end_key) - row_range = RowRange(start_key_closed=start_key, end_key_open=end_key) - expected_result = _ReadRowsRequestPB(table_name=table_name) - expected_result.rows.row_ranges.append(row_range) + result = _create_row_request(start_key=start_key, end_key=end_key) + expected_result = ReadRowsQuery( + row_ranges=RowRange(start_key_closed=start_key, end_key_open=end_key) + ) assert result == expected_result @@ -1679,15 +1335,14 @@ def test__create_row_request_row_range_both_keys_inclusive(): from google.cloud.bigtable.table import _create_row_request from google.cloud.bigtable_v2.types import RowRange - table_name = "table_name" - start_key = b"start_key" + start_key = b"begin_key" end_key = b"end_key" result = _create_row_request( - table_name, start_key=start_key, end_key=end_key, end_inclusive=True + start_key=start_key, end_key=end_key, end_inclusive=True + ) + expected_result = ReadRowsQuery( + row_ranges=RowRange(start_key_closed=start_key, end_key_closed=end_key) ) - expected_result = _ReadRowsRequestPB(table_name=table_name) - row_range = RowRange(start_key_closed=start_key, end_key_closed=end_key) - expected_result.rows.row_ranges.append(row_range) assert result == expected_result @@ -1695,22 +1350,18 @@ def test__create_row_request_with_filter(): from google.cloud.bigtable.row_filters import RowSampleFilter from google.cloud.bigtable.table import _create_row_request - table_name = "table_name" row_filter = RowSampleFilter(0.33) - result = _create_row_request(table_name, filter_=row_filter) - expected_result = _ReadRowsRequestPB( - table_name=table_name, filter=row_filter._to_pb() - ) + result = _create_row_request(filter_=row_filter) + expected_result = ReadRowsQuery(row_filter=row_filter) assert result == expected_result def test__create_row_request_with_limit(): from google.cloud.bigtable.table import _create_row_request - table_name = "table_name" limit = 1337 - result = _create_row_request(table_name, limit=limit) - expected_result = _ReadRowsRequestPB(table_name=table_name, rows_limit=limit) + result = _create_row_request(limit=limit) + expected_result = ReadRowsQuery(limit=limit) assert result == expected_result @@ -1718,32 +1369,12 @@ def test__create_row_request_with_row_set(): from google.cloud.bigtable.row_set import RowSet from google.cloud.bigtable.table import _create_row_request - table_name = "table_name" row_set = RowSet() - result = _create_row_request(table_name, row_set=row_set) - expected_result = _ReadRowsRequestPB(table_name=table_name) - assert result == expected_result - - -def test__create_row_request_with_app_profile_id(): - from google.cloud.bigtable.table import _create_row_request - - table_name = "table_name" - limit = 1337 - app_profile_id = "app-profile-id" - result = _create_row_request(table_name, limit=limit, app_profile_id=app_profile_id) - expected_result = _ReadRowsRequestPB( - table_name=table_name, rows_limit=limit, app_profile_id=app_profile_id - ) + result = _create_row_request(row_set=row_set) + expected_result = ReadRowsQuery() assert result == expected_result -def _ReadRowsRequestPB(*args, **kw): - from google.cloud.bigtable_v2.types import bigtable as messages_v2_pb2 - - return messages_v2_pb2.ReadRowsRequest(*args, **kw) - - def test_cluster_state___eq__(): from google.cloud.bigtable.enums import Table as enum_table from google.cloud.bigtable.table import ClusterState diff --git a/packages/google-cloud-compute-v1beta/CHANGELOG.md b/packages/google-cloud-compute-v1beta/CHANGELOG.md index e443f72414b2..b0d6239448d5 100644 --- a/packages/google-cloud-compute-v1beta/CHANGELOG.md +++ b/packages/google-cloud-compute-v1beta/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-compute-v1beta/#history +## [0.12.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1beta-v0.12.5...google-cloud-compute-v1beta-v0.12.6) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.12.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1beta-v0.12.4...google-cloud-compute-v1beta-v0.12.5) (2026-09-14) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py index f709a40e0d98..1ef1f8093c4f 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py @@ -581,6 +581,10 @@ CalendarModeAdviceRequest, CalendarModeAdviceResponse, CalendarModeAdviceRpcRequest, + CalendarModeExtensionAdviceRequest, + CalendarModeExtensionAdviceResponse, + CalendarModeExtensionAdviceResponseNotRecommendedReason, + CalendarModeExtensionAdviceRpcRequest, CalendarModeRecommendation, CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, @@ -805,6 +809,7 @@ DistributionPolicy, DistributionPolicyZoneConfiguration, Duration, + DynamicCompressionPolicy, EnableXpnHostProjectRequest, EnableXpnResourceProjectRequest, Error, @@ -939,6 +944,7 @@ GetIamPolicyRegionInstantSnapshotRequest, GetIamPolicyRegionNetworkFirewallPolicyRequest, GetIamPolicyRegionSnapshotRequest, + GetIamPolicyRegionSslPolicyRequest, GetIamPolicyReservationBlockRequest, GetIamPolicyReservationRequest, GetIamPolicyReservationSubBlockRequest, @@ -946,6 +952,7 @@ GetIamPolicyServiceAttachmentRequest, GetIamPolicySnapshotGroupRequest, GetIamPolicySnapshotRequest, + GetIamPolicySslPolicyRequest, GetIamPolicyStoragePoolRequest, GetIamPolicySubnetworkRequest, GetImageFamilyViewRequest, @@ -2214,6 +2221,7 @@ SetIamPolicyRegionInstantSnapshotRequest, SetIamPolicyRegionNetworkFirewallPolicyRequest, SetIamPolicyRegionSnapshotRequest, + SetIamPolicyRegionSslPolicyRequest, SetIamPolicyReservationBlockRequest, SetIamPolicyReservationRequest, SetIamPolicyReservationSubBlockRequest, @@ -2221,6 +2229,7 @@ SetIamPolicyServiceAttachmentRequest, SetIamPolicySnapshotGroupRequest, SetIamPolicySnapshotRequest, + SetIamPolicySslPolicyRequest, SetIamPolicyStoragePoolRequest, SetIamPolicySubnetworkRequest, SetInstanceTemplateInstanceGroupManagerRequest, @@ -2995,6 +3004,10 @@ "CalendarModeAdviceRequest", "CalendarModeAdviceResponse", "CalendarModeAdviceRpcRequest", + "CalendarModeExtensionAdviceRequest", + "CalendarModeExtensionAdviceResponse", + "CalendarModeExtensionAdviceResponseNotRecommendedReason", + "CalendarModeExtensionAdviceRpcRequest", "CalendarModeRecommendation", "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", @@ -3219,6 +3232,7 @@ "DistributionPolicy", "DistributionPolicyZoneConfiguration", "Duration", + "DynamicCompressionPolicy", "EnableXpnHostProjectRequest", "EnableXpnResourceProjectRequest", "Error", @@ -3353,6 +3367,7 @@ "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyRegionSnapshotRequest", + "GetIamPolicyRegionSslPolicyRequest", "GetIamPolicyReservationBlockRequest", "GetIamPolicyReservationRequest", "GetIamPolicyReservationSubBlockRequest", @@ -3360,6 +3375,7 @@ "GetIamPolicyServiceAttachmentRequest", "GetIamPolicySnapshotGroupRequest", "GetIamPolicySnapshotRequest", + "GetIamPolicySslPolicyRequest", "GetIamPolicyStoragePoolRequest", "GetIamPolicySubnetworkRequest", "GetImageFamilyViewRequest", @@ -4628,6 +4644,7 @@ "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyRegionSnapshotRequest", + "SetIamPolicyRegionSslPolicyRequest", "SetIamPolicyReservationBlockRequest", "SetIamPolicyReservationRequest", "SetIamPolicyReservationSubBlockRequest", @@ -4635,6 +4652,7 @@ "SetIamPolicyServiceAttachmentRequest", "SetIamPolicySnapshotGroupRequest", "SetIamPolicySnapshotRequest", + "SetIamPolicySslPolicyRequest", "SetIamPolicyStoragePoolRequest", "SetIamPolicySubnetworkRequest", "SetInstanceTemplateInstanceGroupManagerRequest", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute/gapic_version.py b/packages/google-cloud-compute-v1beta/google/cloud/compute/gapic_version.py index 3608c8c9fbc6..bede0e0bec02 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute/gapic_version.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.12.5" # {x-release-please-version} +__version__ = "0.12.6" # {x-release-please-version} diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py index 044621f0d375..b1c2c0af04dd 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py @@ -542,6 +542,10 @@ CalendarModeAdviceRequest, CalendarModeAdviceResponse, CalendarModeAdviceRpcRequest, + CalendarModeExtensionAdviceRequest, + CalendarModeExtensionAdviceResponse, + CalendarModeExtensionAdviceResponseNotRecommendedReason, + CalendarModeExtensionAdviceRpcRequest, CalendarModeRecommendation, CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, @@ -766,6 +770,7 @@ DistributionPolicy, DistributionPolicyZoneConfiguration, Duration, + DynamicCompressionPolicy, EnableXpnHostProjectRequest, EnableXpnResourceProjectRequest, Error, @@ -900,6 +905,7 @@ GetIamPolicyRegionInstantSnapshotRequest, GetIamPolicyRegionNetworkFirewallPolicyRequest, GetIamPolicyRegionSnapshotRequest, + GetIamPolicyRegionSslPolicyRequest, GetIamPolicyReservationBlockRequest, GetIamPolicyReservationRequest, GetIamPolicyReservationSubBlockRequest, @@ -907,6 +913,7 @@ GetIamPolicyServiceAttachmentRequest, GetIamPolicySnapshotGroupRequest, GetIamPolicySnapshotRequest, + GetIamPolicySslPolicyRequest, GetIamPolicyStoragePoolRequest, GetIamPolicySubnetworkRequest, GetImageFamilyViewRequest, @@ -2175,6 +2182,7 @@ SetIamPolicyRegionInstantSnapshotRequest, SetIamPolicyRegionNetworkFirewallPolicyRequest, SetIamPolicyRegionSnapshotRequest, + SetIamPolicyRegionSslPolicyRequest, SetIamPolicyReservationBlockRequest, SetIamPolicyReservationRequest, SetIamPolicyReservationSubBlockRequest, @@ -2182,6 +2190,7 @@ SetIamPolicyServiceAttachmentRequest, SetIamPolicySnapshotGroupRequest, SetIamPolicySnapshotRequest, + SetIamPolicySslPolicyRequest, SetIamPolicyStoragePoolRequest, SetIamPolicySubnetworkRequest, SetInstanceTemplateInstanceGroupManagerRequest, @@ -2821,6 +2830,10 @@ "CalendarModeAdviceRequest", "CalendarModeAdviceResponse", "CalendarModeAdviceRpcRequest", + "CalendarModeExtensionAdviceRequest", + "CalendarModeExtensionAdviceResponse", + "CalendarModeExtensionAdviceResponseNotRecommendedReason", + "CalendarModeExtensionAdviceRpcRequest", "CalendarModeRecommendation", "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", @@ -3050,6 +3063,7 @@ "DistributionPolicy", "DistributionPolicyZoneConfiguration", "Duration", + "DynamicCompressionPolicy", "EnableXpnHostProjectRequest", "EnableXpnResourceProjectRequest", "Error", @@ -3191,6 +3205,7 @@ "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyRegionSnapshotRequest", + "GetIamPolicyRegionSslPolicyRequest", "GetIamPolicyReservationBlockRequest", "GetIamPolicyReservationRequest", "GetIamPolicyReservationSubBlockRequest", @@ -3198,6 +3213,7 @@ "GetIamPolicyServiceAttachmentRequest", "GetIamPolicySnapshotGroupRequest", "GetIamPolicySnapshotRequest", + "GetIamPolicySslPolicyRequest", "GetIamPolicyStoragePoolRequest", "GetIamPolicySubnetworkRequest", "GetImageFamilyViewRequest", @@ -4566,6 +4582,7 @@ "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyRegionSnapshotRequest", + "SetIamPolicyRegionSslPolicyRequest", "SetIamPolicyReservationBlockRequest", "SetIamPolicyReservationRequest", "SetIamPolicyReservationSubBlockRequest", @@ -4573,6 +4590,7 @@ "SetIamPolicyServiceAttachmentRequest", "SetIamPolicySnapshotGroupRequest", "SetIamPolicySnapshotRequest", + "SetIamPolicySslPolicyRequest", "SetIamPolicyStoragePoolRequest", "SetIamPolicySubnetworkRequest", "SetInstanceTemplateInstanceGroupManagerRequest", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json index 71e5541e0fb6..c2bf14b10ee3 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json @@ -88,6 +88,11 @@ "calendar_mode" ] }, + "CalendarModeExtension": { + "methods": [ + "calendar_mode_extension" + ] + }, "Capacity": { "methods": [ "capacity" @@ -4882,6 +4887,11 @@ "get" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "Insert": { "methods": [ "insert" @@ -4902,6 +4912,11 @@ "patch" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "TestIamPermissions": { "methods": [ "test_iam_permissions" @@ -5943,6 +5958,11 @@ "get" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "Insert": { "methods": [ "insert" @@ -5963,6 +5983,11 @@ "patch" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "TestIamPermissions": { "methods": [ "test_iam_permissions" diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py index 3608c8c9fbc6..bede0e0bec02 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.12.5" # {x-release-please-version} +__version__ = "0.12.6" # {x-release-please-version} diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/client.py index 847b17e672cb..0c7445785df2 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/client.py @@ -707,6 +707,152 @@ def sample_calendar_mode(): # Done; return the response. return response + def calendar_mode_extension( + self, + request: Optional[ + Union[compute.CalendarModeExtensionAdviceRpcRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + calendar_mode_extension_advice_request_resource: Optional[ + compute.CalendarModeExtensionAdviceRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CalendarModeExtensionAdviceResponse: + r"""Advises on whether extending an existing future + reservation is possible based on the desired extension + end time. If capacity isn't available for the entire + requested duration, the method recommends the longest + possible extension. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_calendar_mode_extension(): + # Create a client + client = compute_v1beta.AdviceClient() + + # Initialize request argument(s) + request = compute_v1beta.CalendarModeExtensionAdviceRpcRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.calendar_mode_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceRpcRequest, dict]): + The request object. A request message for + Advice.CalendarModeExtension. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + calendar_mode_extension_advice_request_resource (google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceRequest): + The body resource for this request + This corresponds to the ``calendar_mode_extension_advice_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceResponse: + A response that contains the + recommended duration for extending a + future reservation in calendar mode + based on available capacity during the + extension period. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + region, + calendar_mode_extension_advice_request_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CalendarModeExtensionAdviceRpcRequest): + request = compute.CalendarModeExtensionAdviceRpcRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if calendar_mode_extension_advice_request_resource is not None: + request.calendar_mode_extension_advice_request_resource = ( + calendar_mode_extension_advice_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.calendar_mode_extension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def capacity( self, request: Optional[Union[compute.CapacityAdviceRpcRequest, dict]] = None, diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/base.py index 4bd9e88c9534..7965b417fce5 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/base.py @@ -148,6 +148,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.calendar_mode_extension: gapic_v1.method.wrap_method( + self.calendar_mode_extension, + default_timeout=600.0, + client_info=client_info, + ), self.capacity: gapic_v1.method.wrap_method( self.capacity, default_timeout=600.0, @@ -181,6 +186,18 @@ def calendar_mode( ]: raise NotImplementedError() + @property + def calendar_mode_extension( + self, + ) -> Callable[ + [compute.CalendarModeExtensionAdviceRpcRequest], + Union[ + compute.CalendarModeExtensionAdviceResponse, + Awaitable[compute.CalendarModeExtensionAdviceResponse], + ], + ]: + raise NotImplementedError() + @property def capacity( self, diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest.py index b358984b0701..3321c81e91e0 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest.py @@ -80,6 +80,14 @@ def post_calendar_mode(self, response): logging.log(f"Received response: {response}") return response + def pre_calendar_mode_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_calendar_mode_extension(self, response): + logging.log(f"Received response: {response}") + return response + def pre_capacity(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -152,6 +160,58 @@ def post_calendar_mode_with_metadata( """ return response, metadata + def pre_calendar_mode_extension( + self, + request: compute.CalendarModeExtensionAdviceRpcRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CalendarModeExtensionAdviceRpcRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for calendar_mode_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the Advice server. + """ + return request, metadata + + def post_calendar_mode_extension( + self, response: compute.CalendarModeExtensionAdviceResponse + ) -> compute.CalendarModeExtensionAdviceResponse: + """Post-rpc interceptor for calendar_mode_extension + + DEPRECATED. Please use the `post_calendar_mode_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Advice server but before + it is returned to user code. This `post_calendar_mode_extension` interceptor runs + before the `post_calendar_mode_extension_with_metadata` interceptor. + """ + return response + + def post_calendar_mode_extension_with_metadata( + self, + response: compute.CalendarModeExtensionAdviceResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CalendarModeExtensionAdviceResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for calendar_mode_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Advice server but before it is returned to user code. + + We recommend only using this `post_calendar_mode_extension_with_metadata` + interceptor in new development instead of the `post_calendar_mode_extension` interceptor. + When both interceptors are used, this `post_calendar_mode_extension_with_metadata` interceptor runs after the + `post_calendar_mode_extension` interceptor. The (possibly modified) response returned by + `post_calendar_mode_extension` will be passed to + `post_calendar_mode_extension_with_metadata`. + """ + return response, metadata + def pre_capacity( self, request: compute.CapacityAdviceRpcRequest, @@ -503,6 +563,164 @@ def __call__( ) return resp + class _CalendarModeExtension( + _BaseAdviceRestTransport._BaseCalendarModeExtension, AdviceRestStub + ): + def __hash__(self): + return hash("AdviceRestTransport.CalendarModeExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.CalendarModeExtensionAdviceRpcRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CalendarModeExtensionAdviceResponse: + r"""Call the calendar mode extension method over HTTP. + + Args: + request (~.compute.CalendarModeExtensionAdviceRpcRequest): + The request object. A request message for + Advice.CalendarModeExtension. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.CalendarModeExtensionAdviceResponse: + A response that contains the + recommended duration for extending a + future reservation in calendar mode + based on available capacity during the + extension period. + + """ + + http_options = ( + _BaseAdviceRestTransport._BaseCalendarModeExtension._get_http_options() + ) + request, metadata = self._interceptor.pre_calendar_mode_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAdviceRestTransport._BaseCalendarModeExtension, + "_BaseCalendarModeExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1beta.AdviceClient.CalendarModeExtension", + extra={ + "serviceName": "google.cloud.compute.v1beta.Advice", + "rpcName": "CalendarModeExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdviceRestTransport._CalendarModeExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.CalendarModeExtensionAdviceResponse() + pb_resp = compute.CalendarModeExtensionAdviceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_calendar_mode_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_calendar_mode_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + compute.CalendarModeExtensionAdviceResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1beta.AdviceClient.calendar_mode_extension", + extra={ + "serviceName": "google.cloud.compute.v1beta.Advice", + "rpcName": "CalendarModeExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _Capacity(_BaseAdviceRestTransport._BaseCapacity, AdviceRestStub): def __hash__(self): return hash("AdviceRestTransport.Capacity") @@ -811,6 +1029,17 @@ def calendar_mode( # In C++ this would require a dynamic_cast return self._CalendarMode(self._session, self._host, self._interceptor) # type: ignore + @property + def calendar_mode_extension( + self, + ) -> Callable[ + [compute.CalendarModeExtensionAdviceRpcRequest], + compute.CalendarModeExtensionAdviceResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CalendarModeExtension(self._session, self._host, self._interceptor) # type: ignore + @property def capacity( self, diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest_base.py index ae3c675754dc..dc7de2a390fc 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest_base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/advice/transports/rest_base.py @@ -104,6 +104,23 @@ def _get_http_options(): ] return http_options + class _BaseCalendarModeExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/beta/projects/{project}/regions/{region}/advice/calendarModeExtension", + "body": "calendar_mode_extension_advice_request_resource", + }, + ] + return http_options + class _BaseCapacity: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/client.py index eaedafa2f11f..52d9970b9cee 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/client.py @@ -1019,6 +1019,172 @@ def sample_get(): # Done; return the response. return response + def get_iam_policy( + self, + request: Optional[ + Union[compute.GetIamPolicyRegionSslPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Gets the access control policy for a resource. May be + empty if no such policy or resource exists. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_get_iam_policy(): + # Create a client + client = compute_v1beta.RegionSslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetIamPolicyRegionSslPolicyRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetIamPolicyRegionSslPolicyRequest, dict]): + The request object. A request message for + RegionSslPolicies.GetIamPolicy. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1beta.types.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, region, resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetIamPolicyRegionSslPolicyRequest): + request = compute.GetIamPolicyRegionSslPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def insert_unary( self, request: Optional[Union[compute.InsertRegionSslPolicyRequest, dict]] = None, @@ -1886,6 +2052,189 @@ def error_code(self): # Done; return the response. return response + def set_iam_policy( + self, + request: Optional[ + Union[compute.SetIamPolicyRegionSslPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + region_set_policy_request_resource: Optional[ + compute.RegionSetPolicyRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_set_iam_policy(): + # Create a client + client = compute_v1beta.RegionSslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.SetIamPolicyRegionSslPolicyRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.SetIamPolicyRegionSslPolicyRequest, dict]): + The request object. A request message for + RegionSslPolicies.SetIamPolicy. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_set_policy_request_resource (google.cloud.compute_v1beta.types.RegionSetPolicyRequest): + The body resource for this request + This corresponds to the ``region_set_policy_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1beta.types.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + region, + resource, + region_set_policy_request_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.SetIamPolicyRegionSslPolicyRequest): + request = compute.SetIamPolicyRegionSslPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + if region_set_policy_request_resource is not None: + request.region_set_policy_request_resource = ( + region_set_policy_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def test_iam_permissions( self, request: Optional[ diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/base.py index 072d8fa2eb2c..2c616a4e37cd 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/base.py @@ -165,6 +165,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), self.insert: gapic_v1.method.wrap_method( self.insert, default_timeout=600.0, @@ -205,6 +220,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=600.0, + client_info=client_info, + ), self.test_iam_permissions: gapic_v1.method.wrap_method( self.test_iam_permissions, default_timeout=600.0, @@ -239,6 +259,15 @@ def get( ]: raise NotImplementedError() + @property + def get_iam_policy( + self, + ) -> Callable[ + [compute.GetIamPolicyRegionSslPolicyRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + @property def insert( self, @@ -278,6 +307,15 @@ def patch( ]: raise NotImplementedError() + @property + def set_iam_policy( + self, + ) -> Callable[ + [compute.SetIamPolicyRegionSslPolicyRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + @property def test_iam_permissions( self, diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest.py index 54b231040502..0a14fe77b46b 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest.py @@ -88,6 +88,14 @@ def post_get(self, response): logging.log(f"Received response: {response}") return response + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_insert(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -120,6 +128,14 @@ def post_patch(self, response): logging.log(f"Received response: {response}") return response + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_test_iam_permissions(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -226,6 +242,53 @@ def post_get_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: compute.GetIamPolicyRegionSslPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetIamPolicyRegionSslPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionSslPolicies server. + """ + return request, metadata + + def post_get_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for get_iam_policy + + DEPRECATED. Please use the `post_get_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionSslPolicies server but before + it is returned to user code. This `post_get_iam_policy` interceptor runs + before the `post_get_iam_policy_with_metadata` interceptor. + """ + return response + + def post_get_iam_policy_with_metadata( + self, + response: compute.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionSslPolicies server but before it is returned to user code. + + We recommend only using this `post_get_iam_policy_with_metadata` + interceptor in new development instead of the `post_get_iam_policy` interceptor. + When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the + `post_get_iam_policy` interceptor. The (possibly modified) response returned by + `post_get_iam_policy` will be passed to + `post_get_iam_policy_with_metadata`. + """ + return response, metadata + def pre_insert( self, request: compute.InsertRegionSslPolicyRequest, @@ -416,6 +479,53 @@ def post_patch_with_metadata( """ return response, metadata + def pre_set_iam_policy( + self, + request: compute.SetIamPolicyRegionSslPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.SetIamPolicyRegionSslPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionSslPolicies server. + """ + return request, metadata + + def post_set_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for set_iam_policy + + DEPRECATED. Please use the `post_set_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionSslPolicies server but before + it is returned to user code. This `post_set_iam_policy` interceptor runs + before the `post_set_iam_policy_with_metadata` interceptor. + """ + return response + + def post_set_iam_policy_with_metadata( + self, + response: compute.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionSslPolicies server but before it is returned to user code. + + We recommend only using this `post_set_iam_policy_with_metadata` + interceptor in new development instead of the `post_set_iam_policy` interceptor. + When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the + `post_set_iam_policy` interceptor. The (possibly modified) response returned by + `post_set_iam_policy` will be passed to + `post_set_iam_policy_with_metadata`. + """ + return response, metadata + def pre_test_iam_permissions( self, request: compute.TestIamPermissionsRegionSslPolicyRequest, @@ -891,6 +1001,225 @@ def __call__( ) return resp + class _GetIamPolicy( + _BaseRegionSslPoliciesRestTransport._BaseGetIamPolicy, RegionSslPoliciesRestStub + ): + def __hash__(self): + return hash("RegionSslPoliciesRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetIamPolicyRegionSslPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.compute.GetIamPolicyRegionSslPolicyRequest): + The request object. A request message for + RegionSslPolicies.GetIamPolicy. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options = _BaseRegionSslPoliciesRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseRegionSslPoliciesRestTransport._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1beta.RegionSslPoliciesClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionSslPolicies", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionSslPoliciesRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Policy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1beta.RegionSslPoliciesClient.get_iam_policy", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionSslPolicies", + "rpcName": "GetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _Insert( _BaseRegionSslPoliciesRestTransport._BaseInsert, RegionSslPoliciesRestStub ): @@ -1544,6 +1873,227 @@ def __call__( ) return resp + class _SetIamPolicy( + _BaseRegionSslPoliciesRestTransport._BaseSetIamPolicy, RegionSslPoliciesRestStub + ): + def __hash__(self): + return hash("RegionSslPoliciesRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.SetIamPolicyRegionSslPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.compute.SetIamPolicyRegionSslPolicyRequest): + The request object. A request message for + RegionSslPolicies.SetIamPolicy. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options = _BaseRegionSslPoliciesRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseRegionSslPoliciesRestTransport._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1beta.RegionSslPoliciesClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionSslPolicies", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionSslPoliciesRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_set_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Policy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1beta.RegionSslPoliciesClient.set_iam_policy", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionSslPolicies", + "rpcName": "SetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _TestIamPermissions( _BaseRegionSslPoliciesRestTransport._BaseTestIamPermissions, RegionSslPoliciesRestStub, @@ -1708,6 +2258,14 @@ def get(self) -> Callable[[compute.GetRegionSslPolicyRequest], compute.SslPolicy # In C++ this would require a dynamic_cast return self._Get(self._session, self._host, self._interceptor) # type: ignore + @property + def get_iam_policy( + self, + ) -> Callable[[compute.GetIamPolicyRegionSslPolicyRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + @property def insert( self, @@ -1743,6 +2301,14 @@ def patch( # In C++ this would require a dynamic_cast return self._Patch(self._session, self._host, self._interceptor) # type: ignore + @property + def set_iam_policy( + self, + ) -> Callable[[compute.SetIamPolicyRegionSslPolicyRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + @property def test_iam_permissions( self, diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest_base.py index e69fcb4f8822..73e7d30225c1 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest_base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_ssl_policies/transports/rest_base.py @@ -119,6 +119,22 @@ def _get_http_options(): ] return http_options + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/beta/projects/{project}/regions/{region}/sslPolicies/{resource}/getIamPolicy", + }, + ] + return http_options + class _BaseInsert: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -185,6 +201,23 @@ def _get_http_options(): ] return http_options + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/beta/projects/{project}/regions/{region}/sslPolicies/{resource}/setIamPolicy", + "body": "region_set_policy_request_resource", + }, + ] + return http_options + class _BaseTestIamPermissions: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/client.py index c89a916cb66d..d55fa115ea5a 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/client.py @@ -1103,6 +1103,158 @@ def sample_get(): # Done; return the response. return response + def get_iam_policy( + self, + request: Optional[Union[compute.GetIamPolicySslPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Gets the access control policy for a resource. May be + empty if no such policy or resource exists. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_get_iam_policy(): + # Create a client + client = compute_v1beta.SslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetIamPolicySslPolicyRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetIamPolicySslPolicyRequest, dict]): + The request object. A request message for + SslPolicies.GetIamPolicy. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1beta.types.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetIamPolicySslPolicyRequest): + request = compute.GetIamPolicySslPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def insert_unary( self, request: Optional[Union[compute.InsertSslPolicyRequest, dict]] = None, @@ -1876,6 +2028,170 @@ def error_code(self): # Done; return the response. return response + def set_iam_policy( + self, + request: Optional[Union[compute.SetIamPolicySslPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + resource: Optional[str] = None, + global_set_policy_request_resource: Optional[ + compute.GlobalSetPolicyRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_set_iam_policy(): + # Create a client + client = compute_v1beta.SslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.SetIamPolicySslPolicyRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.SetIamPolicySslPolicyRequest, dict]): + The request object. A request message for + SslPolicies.SetIamPolicy. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_set_policy_request_resource (google.cloud.compute_v1beta.types.GlobalSetPolicyRequest): + The body resource for this request + This corresponds to the ``global_set_policy_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1beta.types.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, resource, global_set_policy_request_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.SetIamPolicySslPolicyRequest): + request = compute.SetIamPolicySslPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if resource is not None: + request.resource = resource + if global_set_policy_request_resource is not None: + request.global_set_policy_request_resource = ( + global_set_policy_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def test_iam_permissions( self, request: Optional[ diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/base.py index ca4cc1a1e922..42392d7e1683 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/base.py @@ -180,6 +180,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), self.insert: gapic_v1.method.wrap_method( self.insert, default_timeout=600.0, @@ -220,6 +235,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=600.0, + client_info=client_info, + ), self.test_iam_permissions: gapic_v1.method.wrap_method( self.test_iam_permissions, default_timeout=600.0, @@ -266,6 +286,15 @@ def get( ]: raise NotImplementedError() + @property + def get_iam_policy( + self, + ) -> Callable[ + [compute.GetIamPolicySslPolicyRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + @property def insert( self, @@ -305,6 +334,15 @@ def patch( ]: raise NotImplementedError() + @property + def set_iam_policy( + self, + ) -> Callable[ + [compute.SetIamPolicySslPolicyRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + @property def test_iam_permissions( self, diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest.py index b65d6378a173..03872d5e0409 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest.py @@ -96,6 +96,14 @@ def post_get(self, response): logging.log(f"Received response: {response}") return response + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_insert(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -128,6 +136,14 @@ def post_patch(self, response): logging.log(f"Received response: {response}") return response + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_test_iam_permissions(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -281,6 +297,52 @@ def post_get_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: compute.GetIamPolicySslPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetIamPolicySslPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SslPolicies server. + """ + return request, metadata + + def post_get_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for get_iam_policy + + DEPRECATED. Please use the `post_get_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SslPolicies server but before + it is returned to user code. This `post_get_iam_policy` interceptor runs + before the `post_get_iam_policy_with_metadata` interceptor. + """ + return response + + def post_get_iam_policy_with_metadata( + self, + response: compute.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SslPolicies server but before it is returned to user code. + + We recommend only using this `post_get_iam_policy_with_metadata` + interceptor in new development instead of the `post_get_iam_policy` interceptor. + When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the + `post_get_iam_policy` interceptor. The (possibly modified) response returned by + `post_get_iam_policy` will be passed to + `post_get_iam_policy_with_metadata`. + """ + return response, metadata + def pre_insert( self, request: compute.InsertSslPolicyRequest, @@ -465,6 +527,52 @@ def post_patch_with_metadata( """ return response, metadata + def pre_set_iam_policy( + self, + request: compute.SetIamPolicySslPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.SetIamPolicySslPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SslPolicies server. + """ + return request, metadata + + def post_set_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for set_iam_policy + + DEPRECATED. Please use the `post_set_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SslPolicies server but before + it is returned to user code. This `post_set_iam_policy` interceptor runs + before the `post_set_iam_policy_with_metadata` interceptor. + """ + return response + + def post_set_iam_policy_with_metadata( + self, + response: compute.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SslPolicies server but before it is returned to user code. + + We recommend only using this `post_set_iam_policy_with_metadata` + interceptor in new development instead of the `post_set_iam_policy` interceptor. + When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the + `post_set_iam_policy` interceptor. The (possibly modified) response returned by + `post_set_iam_policy` will be passed to + `post_set_iam_policy_with_metadata`. + """ + return response, metadata + def pre_test_iam_permissions( self, request: compute.TestIamPermissionsSslPolicyRequest, @@ -1083,6 +1191,227 @@ def __call__( ) return resp + class _GetIamPolicy( + _BaseSslPoliciesRestTransport._BaseGetIamPolicy, SslPoliciesRestStub + ): + def __hash__(self): + return hash("SslPoliciesRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetIamPolicySslPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.compute.GetIamPolicySslPolicyRequest): + The request object. A request message for + SslPolicies.GetIamPolicy. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options = ( + _BaseSslPoliciesRestTransport._BaseGetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSslPoliciesRestTransport._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1beta.SslPoliciesClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.compute.v1beta.SslPolicies", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SslPoliciesRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Policy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1beta.SslPoliciesClient.get_iam_policy", + extra={ + "serviceName": "google.cloud.compute.v1beta.SslPolicies", + "rpcName": "GetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _Insert(_BaseSslPoliciesRestTransport._BaseInsert, SslPoliciesRestStub): def __hash__(self): return hash("SslPoliciesRestTransport.Insert") @@ -1721,6 +2050,229 @@ def __call__( ) return resp + class _SetIamPolicy( + _BaseSslPoliciesRestTransport._BaseSetIamPolicy, SslPoliciesRestStub + ): + def __hash__(self): + return hash("SslPoliciesRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.SetIamPolicySslPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.compute.SetIamPolicySslPolicyRequest): + The request object. A request message for + SslPolicies.SetIamPolicy. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options = ( + _BaseSslPoliciesRestTransport._BaseSetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSslPoliciesRestTransport._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1beta.SslPoliciesClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.compute.v1beta.SslPolicies", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SslPoliciesRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_set_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Policy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1beta.SslPoliciesClient.set_iam_policy", + extra={ + "serviceName": "google.cloud.compute.v1beta.SslPolicies", + "rpcName": "SetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _TestIamPermissions( _BaseSslPoliciesRestTransport._BaseTestIamPermissions, SslPoliciesRestStub ): @@ -1892,6 +2444,14 @@ def get(self) -> Callable[[compute.GetSslPolicyRequest], compute.SslPolicy]: # In C++ this would require a dynamic_cast return self._Get(self._session, self._host, self._interceptor) # type: ignore + @property + def get_iam_policy( + self, + ) -> Callable[[compute.GetIamPolicySslPolicyRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + @property def insert(self) -> Callable[[compute.InsertSslPolicyRequest], compute.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -1923,6 +2483,14 @@ def patch(self) -> Callable[[compute.PatchSslPolicyRequest], compute.Operation]: # In C++ this would require a dynamic_cast return self._Patch(self._session, self._host, self._interceptor) # type: ignore + @property + def set_iam_policy( + self, + ) -> Callable[[compute.SetIamPolicySslPolicyRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + @property def test_iam_permissions( self, diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest_base.py index e033a5c4c5b9..432acef5d9a7 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest_base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/ssl_policies/transports/rest_base.py @@ -135,6 +135,22 @@ def _get_http_options(): ] return http_options + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/beta/projects/{project}/global/sslPolicies/{resource}/getIamPolicy", + }, + ] + return http_options + class _BaseInsert: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -201,6 +217,23 @@ def _get_http_options(): ] return http_options + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/beta/projects/{project}/global/sslPolicies/{resource}/setIamPolicy", + "body": "global_set_policy_request_resource", + }, + ] + return http_options + class _BaseTestIamPermissions: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py index 1489a3b1b15b..8b0571d4ed41 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py @@ -227,6 +227,10 @@ CalendarModeAdviceRequest, CalendarModeAdviceResponse, CalendarModeAdviceRpcRequest, + CalendarModeExtensionAdviceRequest, + CalendarModeExtensionAdviceResponse, + CalendarModeExtensionAdviceResponseNotRecommendedReason, + CalendarModeExtensionAdviceRpcRequest, CalendarModeRecommendation, CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, @@ -451,6 +455,7 @@ DistributionPolicy, DistributionPolicyZoneConfiguration, Duration, + DynamicCompressionPolicy, EnableXpnHostProjectRequest, EnableXpnResourceProjectRequest, Error, @@ -585,6 +590,7 @@ GetIamPolicyRegionInstantSnapshotRequest, GetIamPolicyRegionNetworkFirewallPolicyRequest, GetIamPolicyRegionSnapshotRequest, + GetIamPolicyRegionSslPolicyRequest, GetIamPolicyReservationBlockRequest, GetIamPolicyReservationRequest, GetIamPolicyReservationSubBlockRequest, @@ -592,6 +598,7 @@ GetIamPolicyServiceAttachmentRequest, GetIamPolicySnapshotGroupRequest, GetIamPolicySnapshotRequest, + GetIamPolicySslPolicyRequest, GetIamPolicyStoragePoolRequest, GetIamPolicySubnetworkRequest, GetImageFamilyViewRequest, @@ -1860,6 +1867,7 @@ SetIamPolicyRegionInstantSnapshotRequest, SetIamPolicyRegionNetworkFirewallPolicyRequest, SetIamPolicyRegionSnapshotRequest, + SetIamPolicyRegionSslPolicyRequest, SetIamPolicyReservationBlockRequest, SetIamPolicyReservationRequest, SetIamPolicyReservationSubBlockRequest, @@ -1867,6 +1875,7 @@ SetIamPolicyServiceAttachmentRequest, SetIamPolicySnapshotGroupRequest, SetIamPolicySnapshotRequest, + SetIamPolicySslPolicyRequest, SetIamPolicyStoragePoolRequest, SetIamPolicySubnetworkRequest, SetInstanceTemplateInstanceGroupManagerRequest, @@ -2500,6 +2509,10 @@ "CalendarModeAdviceRequest", "CalendarModeAdviceResponse", "CalendarModeAdviceRpcRequest", + "CalendarModeExtensionAdviceRequest", + "CalendarModeExtensionAdviceResponse", + "CalendarModeExtensionAdviceResponseNotRecommendedReason", + "CalendarModeExtensionAdviceRpcRequest", "CalendarModeRecommendation", "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", @@ -2724,6 +2737,7 @@ "DistributionPolicy", "DistributionPolicyZoneConfiguration", "Duration", + "DynamicCompressionPolicy", "EnableXpnHostProjectRequest", "EnableXpnResourceProjectRequest", "Error", @@ -2858,6 +2872,7 @@ "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyRegionSnapshotRequest", + "GetIamPolicyRegionSslPolicyRequest", "GetIamPolicyReservationBlockRequest", "GetIamPolicyReservationRequest", "GetIamPolicyReservationSubBlockRequest", @@ -2865,6 +2880,7 @@ "GetIamPolicyServiceAttachmentRequest", "GetIamPolicySnapshotGroupRequest", "GetIamPolicySnapshotRequest", + "GetIamPolicySslPolicyRequest", "GetIamPolicyStoragePoolRequest", "GetIamPolicySubnetworkRequest", "GetImageFamilyViewRequest", @@ -4133,6 +4149,7 @@ "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyRegionSnapshotRequest", + "SetIamPolicyRegionSslPolicyRequest", "SetIamPolicyReservationBlockRequest", "SetIamPolicyReservationRequest", "SetIamPolicyReservationSubBlockRequest", @@ -4140,6 +4157,7 @@ "SetIamPolicyServiceAttachmentRequest", "SetIamPolicySnapshotGroupRequest", "SetIamPolicySnapshotRequest", + "SetIamPolicySslPolicyRequest", "SetIamPolicyStoragePoolRequest", "SetIamPolicySubnetworkRequest", "SetInstanceTemplateInstanceGroupManagerRequest", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py index d43c16ba5d3c..946637b5bd71 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py @@ -237,6 +237,10 @@ "CalendarModeAdviceRequest", "CalendarModeAdviceResponse", "CalendarModeAdviceRpcRequest", + "CalendarModeExtensionAdviceRequest", + "CalendarModeExtensionAdviceResponse", + "CalendarModeExtensionAdviceResponseNotRecommendedReason", + "CalendarModeExtensionAdviceRpcRequest", "CalendarModeRecommendation", "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", @@ -461,6 +465,7 @@ "DistributionPolicy", "DistributionPolicyZoneConfiguration", "Duration", + "DynamicCompressionPolicy", "EnableXpnHostProjectRequest", "EnableXpnResourceProjectRequest", "Error", @@ -597,6 +602,7 @@ "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyRegionSnapshotRequest", + "GetIamPolicyRegionSslPolicyRequest", "GetIamPolicyReservationBlockRequest", "GetIamPolicyReservationRequest", "GetIamPolicyReservationSubBlockRequest", @@ -604,6 +610,7 @@ "GetIamPolicyServiceAttachmentRequest", "GetIamPolicySnapshotGroupRequest", "GetIamPolicySnapshotRequest", + "GetIamPolicySslPolicyRequest", "GetIamPolicyStoragePoolRequest", "GetIamPolicySubnetworkRequest", "GetImageFamilyViewRequest", @@ -1871,6 +1878,7 @@ "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyRegionSnapshotRequest", + "SetIamPolicyRegionSslPolicyRequest", "SetIamPolicyReservationBlockRequest", "SetIamPolicyReservationRequest", "SetIamPolicyReservationSubBlockRequest", @@ -1878,6 +1886,7 @@ "SetIamPolicyServiceAttachmentRequest", "SetIamPolicySnapshotGroupRequest", "SetIamPolicySnapshotRequest", + "SetIamPolicySslPolicyRequest", "SetIamPolicyStoragePoolRequest", "SetIamPolicySubnetworkRequest", "SetInstanceTemplateInstanceGroupManagerRequest", @@ -16193,6 +16202,18 @@ class AliasIpRange(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + candidate_subnetwork_range_names (MutableSequence[str]): + Identifies the candidate subnetwork range names for the + alias IPs to be allocated from. When it is set, the IP would + be allocated from any subnetwork range defined here if the + IPs are available. Only one of subnetwork_range_name or + candidate_subnetwork_range_names should be set. + effective_subnetwork_range_name (str): + Output only. [Output Only] The subnetwork range name where + the IP is allocated. It will be set to the subnetwork range + where the IP is allocated only. + + This field is a member of `oneof`_ ``_effective_subnetwork_range_name``. ip_cidr_range (str): The IP alias ranges to allocate for this interface. This IP CIDR range must belong to the @@ -16213,6 +16234,15 @@ class AliasIpRange(proto.Message): This field is a member of `oneof`_ ``_subnetwork_range_name``. """ + candidate_subnetwork_range_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=148215089, + ) + effective_subnetwork_range_name: str = proto.Field( + proto.STRING, + number=110951590, + optional=True, + ) ip_cidr_range: str = proto.Field( proto.STRING, number=98117322, @@ -23547,10 +23577,11 @@ class BackendServiceHAPolicyLeaderNetworkEndpoint(proto.Message): attached to the NEG specified in the haPolicy.leader.backendGroup. - The name must be 1-63 characters long, and - comply with RFC1035. Authorization requires the - following IAM permission on the specified - resource instance: compute.instances.use + The value must be a valid RFC1035 name (1-63 + characters) or a valid instance URL. + Authorization requires the following IAM + permission on the specified resource instance: + compute.instances.use This field is a member of `oneof`_ ``_instance``. """ @@ -26624,6 +26655,177 @@ class CalendarModeAdviceRpcRequest(proto.Message): ) +class CalendarModeExtensionAdviceRequest(proto.Message): + r"""A request to recommend the maximum duration for extending an + existing future reservation in calendar mode. The recommended + duration is shorter than or equal to the specified extension + duration. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + end_time_not_later_than (str): + Required. The desired end time for the + extension. + + This field is a member of `oneof`_ ``_end_time_not_later_than``. + future_reservation (str): + Required. Reference to the future + reservation, in the format: + projects/{project}/zones/{zone}/futureReservations/{name} + Full URIs that include hostnames (like + compute.googleapis.com or www.googleapis.com) + are also supported. + + This field is a member of `oneof`_ ``_future_reservation``. + """ + + end_time_not_later_than: str = proto.Field( + proto.STRING, + number=526866094, + optional=True, + ) + future_reservation: str = proto.Field( + proto.STRING, + number=56206160, + optional=True, + ) + + +class CalendarModeExtensionAdviceResponse(proto.Message): + r"""A response that contains the recommended duration for + extending a future reservation in calendar mode based on + available capacity during the extension period. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + end_time (str): + The recommended end time for the extension, + which is either the end time requested by the + caller or the longest alternative with + sufficient capacity. If the extension is not + possible, this field is empty, and + notRecommendedReason is populated instead. + + This field is a member of `oneof`_ ``_end_time``. + not_recommended_reason (google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceResponseNotRecommendedReason): + The reason why the future reservation can't + be extended. If a recommendation is provided, + whether for the requested end time or an + alternative, this field is empty. + + This field is a member of `oneof`_ ``_not_recommended_reason``. + recommendation_id (str): + The unique ID of the recommendation, which is + a UUID string generated by the API. + + This field is a member of `oneof`_ ``_recommendation_id``. + """ + + end_time: str = proto.Field( + proto.STRING, + number=114938801, + optional=True, + ) + not_recommended_reason: "CalendarModeExtensionAdviceResponseNotRecommendedReason" = proto.Field( + proto.MESSAGE, + number=516813204, + optional=True, + message="CalendarModeExtensionAdviceResponseNotRecommendedReason", + ) + recommendation_id: str = proto.Field( + proto.STRING, + number=474540897, + optional=True, + ) + + +class CalendarModeExtensionAdviceResponseNotRecommendedReason(proto.Message): + r"""Information about why no recommendation was provided. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + details (str): + Human-readable details describing why the recommendation + wasn't provided. For example, if the status is + CONDITIONS_NOT_MET, this field explains why the requested + extension duration isn't possible. + + This field is a member of `oneof`_ ``_details``. + status (str): + Status of recommendation. + Check the Status enum for the list of possible + values. + + This field is a member of `oneof`_ ``_status``. + """ + + class Status(proto.Enum): + r"""Status of recommendation. + + Values: + UNDEFINED_STATUS (0): + A value indicating that the enum field is not + set. + CONDITIONS_NOT_MET (363628457): + The requested extension window doesn't meet + the required conditions. + NOT_RECOMMENDED_REASON_STATUS_UNSPECIFIED (183381653): + Default value, unused. + NO_CAPACITY (274240888): + There is no available capacity for the + extension to be provided. + """ + + UNDEFINED_STATUS = 0 + CONDITIONS_NOT_MET = 363628457 + NOT_RECOMMENDED_REASON_STATUS_UNSPECIFIED = 183381653 + NO_CAPACITY = 274240888 + + details: str = proto.Field( + proto.STRING, + number=483979842, + optional=True, + ) + status: str = proto.Field( + proto.STRING, + number=181260274, + optional=True, + ) + + +class CalendarModeExtensionAdviceRpcRequest(proto.Message): + r"""A request message for Advice.CalendarModeExtension. See the + method description for details. + + Attributes: + calendar_mode_extension_advice_request_resource (google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceRequest): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + """ + + calendar_mode_extension_advice_request_resource: "CalendarModeExtensionAdviceRequest" = proto.Field( + proto.MESSAGE, + number=450334890, + message="CalendarModeExtensionAdviceRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class CalendarModeRecommendation(proto.Message): r"""A single recommendation to create requested resources. Contains detailed recommendations for every future resources @@ -27130,7 +27332,7 @@ class TargetShape(proto.Enum): possible across selected zones to minimize the impact of zonal failure. TARGET_SHAPE_UNSPECIFIED (449316907): - No description available. + Default value, unused. """ UNDEFINED_TARGET_SHAPE = 0 @@ -27589,7 +27791,7 @@ class Types(proto.Enum): A value indicating that the enum field is not set. HISTORY_TYPE_UNSPECIFIED (58549757): - No description available. + Default value, unused. PREEMPTION (512869337): Preemption history. PRICE (76396841): @@ -28323,12 +28525,14 @@ class Commitment(proto.Message): GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, - STORAGE_OPTIMIZED_Z3. For example, type MEMORY_OPTIMIZED - specifies a commitment that applies only to eligible - resources of memory optimized M1 and M2 machine series. Type - GENERAL_PURPOSE specifies a commitment that applies only to - eligible resources of general purpose N1 machine series. - Check the Type enum for the list of possible values. + STORAGE_OPTIMIZED_Z3,STORAGE_OPTIMIZED_Z4DS, + STORAGE_OPTIMIZED_Z4DH,STORAGE_OPTIMIZED_Z4D4T. For example, + type MEMORY_OPTIMIZED specifies a commitment that applies + only to eligible resources of memory optimized M1 and M2 + machine series. Type GENERAL_PURPOSE specifies a commitment + that applies only to eligible resources of general purpose + N1 machine series. Check the Type enum for the list of + possible values. This field is a member of `oneof`_ ``_type``. """ @@ -28435,11 +28639,13 @@ class Type(proto.Enum): GENERAL_PURPOSE_N2D,GENERAL_PURPOSE_N4, GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, - MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, STORAGE_OPTIMIZED_Z3. For - example, type MEMORY_OPTIMIZED specifies a commitment that applies - only to eligible resources of memory optimized M1 and M2 machine - series. Type GENERAL_PURPOSE specifies a commitment that applies - only to eligible resources of general purpose N1 machine series. + MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, + STORAGE_OPTIMIZED_Z3,STORAGE_OPTIMIZED_Z4DS, + STORAGE_OPTIMIZED_Z4DH,STORAGE_OPTIMIZED_Z4D4T. For example, type + MEMORY_OPTIMIZED specifies a commitment that applies only to + eligible resources of memory optimized M1 and M2 machine series. + Type GENERAL_PURPOSE specifies a commitment that applies only to + eligible resources of general purpose N1 machine series. Values: UNDEFINED_TYPE (0): @@ -28537,6 +28743,12 @@ class Type(proto.Enum): CUD bucket for NETWORK_OPTIMIZED_U4S machines. STORAGE_OPTIMIZED_Z3 (316796085): No description available. + STORAGE_OPTIMIZED_Z4D4T (18503022): + CUD bucket for Z4D-4T machines. + STORAGE_OPTIMIZED_Z4DH (35233722): + CUD bucket for Z4DH machines. + STORAGE_OPTIMIZED_Z4DS (35233733): + CUD bucket for Z4DS machines. TYPE_UNSPECIFIED (437714322): Note for internal users: When adding a new enum Type for v1, make sure to also add it in the comment for the @@ -28588,6 +28800,9 @@ class Type(proto.Enum): NETWORK_OPTIMIZED_U4P = 147044872 NETWORK_OPTIMIZED_U4S = 147044875 STORAGE_OPTIMIZED_Z3 = 316796085 + STORAGE_OPTIMIZED_Z4D4T = 18503022 + STORAGE_OPTIMIZED_Z4DH = 35233722 + STORAGE_OPTIMIZED_Z4DS = 35233733 TYPE_UNSPECIFIED = 437714322 auto_renew: bool = proto.Field( @@ -40394,6 +40609,51 @@ class Duration(proto.Message): ) +class DynamicCompressionPolicy(proto.Message): + r"""Dynamic compression policy for this URL Map's route. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + compression_mode (str): + Compress text responses using Brotli or gzip + compression, based on the client's + Accept-Encoding header. Check the + CompressionMode enum for the list of possible + values. + + This field is a member of `oneof`_ ``_compression_mode``. + """ + + class CompressionMode(proto.Enum): + r"""Compress text responses using Brotli or gzip compression, + based on the client's Accept-Encoding header. + + Values: + UNDEFINED_COMPRESSION_MODE (0): + A value indicating that the enum field is not + set. + AUTOMATIC (165298699): + Automatically uses the best compression based + on the Accept-Encoding header sent by the + client. + DISABLED (516696700): + Disables compression. Existing compressed + responses cached by Cloud CDN will not be served + to clients. + """ + + UNDEFINED_COMPRESSION_MODE = 0 + AUTOMATIC = 165298699 + DISABLED = 516696700 + + compression_mode: str = proto.Field( + proto.STRING, + number=95520988, + optional=True, + ) + + class EnableXpnHostProjectRequest(proto.Message): r"""A request message for Projects.EnableXpnHost. See the method description for details. @@ -49307,6 +49567,45 @@ class GetIamPolicyRegionSnapshotRequest(proto.Message): ) +class GetIamPolicyRegionSslPolicyRequest(proto.Message): + r"""A request message for RegionSslPolicies.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + class GetIamPolicyReservationBlockRequest(proto.Message): r"""A request message for ReservationBlocks.GetIamPolicy. See the method description for details. @@ -49582,6 +49881,39 @@ class GetIamPolicySnapshotRequest(proto.Message): ) +class GetIamPolicySslPolicyRequest(proto.Message): + r"""A request message for SslPolicies.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + class GetIamPolicyStoragePoolRequest(proto.Message): r"""A request message for StoragePools.GetIamPolicy. See the method description for details. @@ -55446,6 +55778,9 @@ class Type(proto.Enum): set. BARE_METAL_LINUX_COMPATIBLE (354232740): No description available. + BMSAI_CAPABLE (449302109): + Indicates the guest OS is capable of Bare + Metal Secure AI (BMSAI) confidential computing. CCA_CAPABLE (79012270): No description available. FEATURE_TYPE_UNSPECIFIED (531767259): @@ -55483,6 +55818,7 @@ class Type(proto.Enum): UNDEFINED_TYPE = 0 BARE_METAL_LINUX_COMPATIBLE = 354232740 + BMSAI_CAPABLE = 449302109 CCA_CAPABLE = 79012270 FEATURE_TYPE_UNSPECIFIED = 531767259 GVNIC = 68209305 @@ -59485,6 +59821,12 @@ class HttpRouteAction(proto.Message): target gRPC proxy. This field is a member of `oneof`_ ``_cors_policy``. + dynamic_compression_policy (google.cloud.compute_v1beta.types.DynamicCompressionPolicy): + Dynamic compression policy for this URL Map's route. + Available only for Global EXTERNAL_MANAGED load balancer + schemes. + + This field is a member of `oneof`_ ``_dynamic_compression_policy``. fault_injection_policy (google.cloud.compute_v1beta.types.HttpFaultInjection): The specification for fault injection introduced into traffic to test the resiliency of clients to backend service @@ -59605,6 +59947,12 @@ class HttpRouteAction(proto.Message): optional=True, message="CorsPolicy", ) + dynamic_compression_policy: "DynamicCompressionPolicy" = proto.Field( + proto.MESSAGE, + number=356626987, + optional=True, + message="DynamicCompressionPolicy", + ) fault_injection_policy: "HttpFaultInjection" = proto.Field( proto.MESSAGE, number=412781079, @@ -72781,7 +73129,15 @@ class InstancePropertiesPatch(proto.Message): r"""Represents the change that you want to make to the instance properties. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: + expose_host_topology (bool): + This optional flag exposes the hashed + physical host ID. + + This field is a member of `oneof`_ ``_expose_host_topology``. labels (MutableMapping[str, str]): The label key-value pairs that you want to patch onto the instance. @@ -72791,6 +73147,11 @@ class InstancePropertiesPatch(proto.Message): see Project and instance metadata. """ + expose_host_topology: bool = proto.Field( + proto.BOOL, + number=428530155, + optional=True, + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -80413,6 +80774,13 @@ class InterconnectMacsec(proto.Message): with your router. This field is a member of `oneof`_ ``_fail_open``. + interconnect_key_group (str): + Optional. URL of the InterconnectKeyGroup + resource to use for MACsec, in the format: + + projects/{project}/locations/{region}/interconnectKeyGroups/{interconnectKeyGroup}. + + This field is a member of `oneof`_ ``_interconnect_key_group``. pre_shared_keys (MutableSequence[google.cloud.compute_v1beta.types.InterconnectMacsecPreSharedKey]): Required. A keychain placeholder describing a set of named key objects along with their start @@ -80428,6 +80796,11 @@ class InterconnectMacsec(proto.Message): number=532597451, optional=True, ) + interconnect_key_group: str = proto.Field( + proto.STRING, + number=304265774, + optional=True, + ) pre_shared_keys: MutableSequence["InterconnectMacsecPreSharedKey"] = ( proto.RepeatedField( proto.MESSAGE, @@ -139997,6 +140370,12 @@ class ResourceStatusPhysicalHostTopology(proto.Message): the lowest possible network latency. This field is a member of `oneof`_ ``_host``. + machine (str): + Output only. [Output Only] The ID of the machine on which + the running instance is located. It is only populated for + machines which have multiple hosts. + + This field is a member of `oneof`_ ``_machine``. subblock (str): [Output Only] The ID of the sub-block in which the running instance is located. Instances in the same sub-block @@ -140029,6 +140408,11 @@ class ResourceStatusPhysicalHostTopology(proto.Message): number=3208616, optional=True, ) + machine: str = proto.Field( + proto.STRING, + number=288441415, + optional=True, + ) subblock: str = proto.Field( proto.STRING, number=70446669, @@ -146305,6 +146689,12 @@ class Scheduling(proto.Message): attached to the instance. This field is a member of `oneof`_ ``_availability_domain``. + expose_host_topology (bool): + This optional flag exposes the hashed + physical host ID in the ResourceStatus resource + of the VM. + + This field is a member of `oneof`_ ``_expose_host_topology``. graceful_shutdown (google.cloud.compute_v1beta.types.SchedulingGracefulShutdown): This field is a member of `oneof`_ ``_graceful_shutdown``. @@ -146544,6 +146934,11 @@ class ProvisioningModel(proto.Enum): number=252514344, optional=True, ) + expose_host_topology: bool = proto.Field( + proto.BOOL, + number=428530155, + optional=True, + ) graceful_shutdown: "SchedulingGracefulShutdown" = proto.Field( proto.MESSAGE, number=226325136, @@ -152271,6 +152666,40 @@ class SetIamPolicyRegionSnapshotRequest(proto.Message): ) +class SetIamPolicyRegionSslPolicyRequest(proto.Message): + r"""A request message for RegionSslPolicies.SetIamPolicy. See the + method description for details. + + Attributes: + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + region_set_policy_request_resource (google.cloud.compute_v1beta.types.RegionSetPolicyRequest): + The body resource for this request + resource (str): + Name or id of the resource for this request. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_set_policy_request_resource: "RegionSetPolicyRequest" = proto.Field( + proto.MESSAGE, + number=276489091, + message="RegionSetPolicyRequest", + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + class SetIamPolicyReservationBlockRequest(proto.Message): r"""A request message for ReservationBlocks.SetIamPolicy. See the method description for details. @@ -152511,6 +152940,34 @@ class SetIamPolicySnapshotRequest(proto.Message): ) +class SetIamPolicySslPolicyRequest(proto.Message): + r"""A request message for SslPolicies.SetIamPolicy. See the + method description for details. + + Attributes: + global_set_policy_request_resource (google.cloud.compute_v1beta.types.GlobalSetPolicyRequest): + The body resource for this request + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + """ + + global_set_policy_request_resource: "GlobalSetPolicyRequest" = proto.Field( + proto.MESSAGE, + number=337048498, + message="GlobalSetPolicyRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + class SetIamPolicyStoragePoolRequest(proto.Message): r"""A request message for StoragePools.SetIamPolicy. See the method description for details. diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_advice_calendar_mode_extension_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_advice_calendar_mode_extension_sync.py new file mode 100644 index 000000000000..17dd61221e51 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_advice_calendar_mode_extension_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CalendarModeExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute-v1beta + + +# [START compute_v1beta_generated_Advice_CalendarModeExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1beta + + +def sample_calendar_mode_extension(): + # Create a client + client = compute_v1beta.AdviceClient() + + # Initialize request argument(s) + request = compute_v1beta.CalendarModeExtensionAdviceRpcRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.calendar_mode_extension(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_Advice_CalendarModeExtension_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_ssl_policies_get_iam_policy_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_ssl_policies_get_iam_policy_sync.py new file mode 100644 index 000000000000..932c8b4788b4 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_ssl_policies_get_iam_policy_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute-v1beta + + +# [START compute_v1beta_generated_RegionSslPolicies_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1beta + + +def sample_get_iam_policy(): + # Create a client + client = compute_v1beta.RegionSslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetIamPolicyRegionSslPolicyRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_RegionSslPolicies_GetIamPolicy_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_ssl_policies_set_iam_policy_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_ssl_policies_set_iam_policy_sync.py new file mode 100644 index 000000000000..97f7a15ac58e --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_ssl_policies_set_iam_policy_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute-v1beta + + +# [START compute_v1beta_generated_RegionSslPolicies_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1beta + + +def sample_set_iam_policy(): + # Create a client + client = compute_v1beta.RegionSslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.SetIamPolicyRegionSslPolicyRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_RegionSslPolicies_SetIamPolicy_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_ssl_policies_get_iam_policy_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_ssl_policies_get_iam_policy_sync.py new file mode 100644 index 000000000000..d552b0a51759 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_ssl_policies_get_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute-v1beta + + +# [START compute_v1beta_generated_SslPolicies_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1beta + + +def sample_get_iam_policy(): + # Create a client + client = compute_v1beta.SslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetIamPolicySslPolicyRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_SslPolicies_GetIamPolicy_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_ssl_policies_set_iam_policy_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_ssl_policies_set_iam_policy_sync.py new file mode 100644 index 000000000000..d6e9b69b628b --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_ssl_policies_set_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute-v1beta + + +# [START compute_v1beta_generated_SslPolicies_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1beta + + +def sample_set_iam_policy(): + # Create a client + client = compute_v1beta.SslPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.SetIamPolicySslPolicyRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_SslPolicies_SetIamPolicy_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json index dc61ab586bfa..0fc82c72cae9 100644 --- a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-compute-v1beta", - "version": "0.12.5" + "version": "0.12.6" }, "snippets": [ { @@ -967,6 +967,94 @@ ], "title": "compute_v1beta_generated_addresses_test_iam_permissions_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.AdviceClient", + "shortName": "AdviceClient" + }, + "fullName": "google.cloud.compute_v1beta.AdviceClient.calendar_mode_extension", + "method": { + "fullName": "google.cloud.compute.v1beta.Advice.CalendarModeExtension", + "service": { + "fullName": "google.cloud.compute.v1beta.Advice", + "shortName": "Advice" + }, + "shortName": "CalendarModeExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceRpcRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "calendar_mode_extension_advice_request_resource", + "type": "google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1beta.types.CalendarModeExtensionAdviceResponse", + "shortName": "calendar_mode_extension" + }, + "description": "Sample for CalendarModeExtension", + "file": "compute_v1beta_generated_advice_calendar_mode_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Advice_CalendarModeExtension_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_advice_calendar_mode_extension_sync.py" + }, { "canonical": true, "clientMethod": { @@ -69399,6 +69487,94 @@ ], "title": "compute_v1beta_generated_region_ssl_policies_delete_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionSslPoliciesClient", + "shortName": "RegionSslPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionSslPoliciesClient.get_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionSslPolicies.GetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionSslPolicies", + "shortName": "RegionSslPolicies" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetIamPolicyRegionSslPolicyRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1beta.types.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "compute_v1beta_generated_region_ssl_policies_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionSslPolicies_GetIamPolicy_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_region_ssl_policies_get_iam_policy_sync.py" + }, { "canonical": true, "clientMethod": { @@ -69835,6 +70011,98 @@ ], "title": "compute_v1beta_generated_region_ssl_policies_patch_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionSslPoliciesClient", + "shortName": "RegionSslPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionSslPoliciesClient.set_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionSslPolicies.SetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionSslPolicies", + "shortName": "RegionSslPolicies" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.SetIamPolicyRegionSslPolicyRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionSetPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1beta.types.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "compute_v1beta_generated_region_ssl_policies_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionSslPolicies_SetIamPolicy_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_region_ssl_policies_set_iam_policy_sync.py" + }, { "canonical": true, "clientMethod": { @@ -84163,6 +84431,90 @@ ], "title": "compute_v1beta_generated_ssl_policies_delete_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.SslPoliciesClient", + "shortName": "SslPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.SslPoliciesClient.get_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1beta.SslPolicies.GetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1beta.SslPolicies", + "shortName": "SslPolicies" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetIamPolicySslPolicyRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1beta.types.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "compute_v1beta_generated_ssl_policies_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_SslPolicies_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_ssl_policies_get_iam_policy_sync.py" + }, { "canonical": true, "clientMethod": { @@ -84579,6 +84931,94 @@ ], "title": "compute_v1beta_generated_ssl_policies_patch_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.SslPoliciesClient", + "shortName": "SslPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.SslPoliciesClient.set_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1beta.SslPolicies.SetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1beta.SslPolicies", + "shortName": "SslPolicies" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.SetIamPolicySslPolicyRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "global_set_policy_request_resource", + "type": "google.cloud.compute_v1beta.types.GlobalSetPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1beta.types.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "compute_v1beta_generated_ssl_policies_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_SslPolicies_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_ssl_policies_set_iam_policy_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_advice.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_advice.py index 4d6ea753f3c4..6eee118d801e 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_advice.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_advice.py @@ -1073,6 +1073,193 @@ def test_calendar_mode_rest_flattened_error(transport: str = "rest"): ) +def test_calendar_mode_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.calendar_mode_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.calendar_mode_extension + ] = mock_rpc + + request = {} + client.calendar_mode_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.calendar_mode_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_calendar_mode_extension_rest_required_fields( + request_type=compute.CalendarModeExtensionAdviceRpcRequest, +): + transport_class = transports.AdviceRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCalendarModeExtension, + "_BaseCalendarModeExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.CalendarModeExtensionAdviceResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CalendarModeExtensionAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.calendar_mode_extension(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_calendar_mode_extension_rest_flattened(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CalendarModeExtensionAdviceResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + calendar_mode_extension_advice_request_resource=compute.CalendarModeExtensionAdviceRequest( + end_time_not_later_than="end_time_not_later_than_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.CalendarModeExtensionAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.calendar_mode_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/regions/{region}/advice/calendarModeExtension" + % client.transport._host, + args[1], + ) + + +def test_calendar_mode_extension_rest_flattened_error(transport: str = "rest"): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.calendar_mode_extension( + compute.CalendarModeExtensionAdviceRpcRequest(), + project="project_value", + region="region_value", + calendar_mode_extension_advice_request_resource=compute.CalendarModeExtensionAdviceRequest( + end_time_not_later_than="end_time_not_later_than_value" + ), + ) + + def test_capacity_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1732,6 +1919,228 @@ def test_calendar_mode_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_calendar_mode_extension_rest_bad_request( + request_type=compute.CalendarModeExtensionAdviceRpcRequest, +): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.calendar_mode_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CalendarModeExtensionAdviceRpcRequest, + dict, + ], +) +def test_calendar_mode_extension_rest_call_success(request_type): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["calendar_mode_extension_advice_request_resource"] = { + "end_time_not_later_than": "end_time_not_later_than_value", + "future_reservation": "future_reservation_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.CalendarModeExtensionAdviceRpcRequest.meta.fields[ + "calendar_mode_extension_advice_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "calendar_mode_extension_advice_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, + len( + request_init["calendar_mode_extension_advice_request_resource"][ + field + ] + ), + ): + del request_init["calendar_mode_extension_advice_request_resource"][ + field + ][i][subfield] + else: + del request_init["calendar_mode_extension_advice_request_resource"][ + field + ][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CalendarModeExtensionAdviceResponse( + end_time="end_time_value", + recommendation_id="recommendation_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CalendarModeExtensionAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.calendar_mode_extension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.CalendarModeExtensionAdviceResponse) + assert response.end_time == "end_time_value" + assert response.recommendation_id == "recommendation_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_calendar_mode_extension_rest_interceptors(null_interceptor): + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AdviceRestInterceptor(), + ) + client = AdviceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AdviceRestInterceptor, "post_calendar_mode_extension" + ) as post, + mock.patch.object( + transports.AdviceRestInterceptor, + "post_calendar_mode_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AdviceRestInterceptor, "pre_calendar_mode_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CalendarModeExtensionAdviceRpcRequest.pb( + compute.CalendarModeExtensionAdviceRpcRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.CalendarModeExtensionAdviceResponse.to_json( + compute.CalendarModeExtensionAdviceResponse() + ) + req.return_value.content = return_value + + request = compute.CalendarModeExtensionAdviceRpcRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.CalendarModeExtensionAdviceResponse() + post_with_metadata.return_value = ( + compute.CalendarModeExtensionAdviceResponse(), + metadata, + ) + + client.calendar_mode_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_capacity_rest_bad_request(request_type=compute.CapacityAdviceRpcRequest): client = AdviceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2180,6 +2589,27 @@ def test_calendar_mode_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_calendar_mode_extension_empty_call_rest(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.calendar_mode_extension), "__call__" + ) as call: + client.calendar_mode_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CalendarModeExtensionAdviceRpcRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_capacity_empty_call_rest(): @@ -2241,6 +2671,7 @@ def test_advice_base_transport(): # raise NotImplementedError. methods = ( "calendar_mode", + "calendar_mode_extension", "capacity", "capacity_history", ) @@ -2389,6 +2820,9 @@ def test_advice_client_transport_session_collision(transport_name): session1 = client1.transport.calendar_mode._session session2 = client2.transport.calendar_mode._session assert session1 != session2 + session1 = client1.transport.calendar_mode_extension._session + session2 = client2.transport.calendar_mode_extension._session + assert session1 != session2 session1 = client1.transport.capacity._session session2 = client2.transport.capacity._session assert session1 != session2 diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py index c2a6f3386e7d..ad2cb3ca9298 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py @@ -4544,7 +4544,7 @@ def test_insert_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4590,7 +4590,7 @@ def test_insert_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4741,7 +4741,7 @@ def test_insert_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4787,7 +4787,7 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -6017,7 +6017,7 @@ def test_patch_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -6064,7 +6064,7 @@ def test_patch_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -6224,7 +6224,7 @@ def test_patch_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -6271,7 +6271,7 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11123,7 +11123,7 @@ def test_update_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11170,7 +11170,7 @@ def test_update_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11330,7 +11330,7 @@ def test_update_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11377,7 +11377,7 @@ def test_update_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -14207,7 +14207,9 @@ def test_insert_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"project": "sample1", "zone": "sample2"} request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -15206,7 +15208,9 @@ def test_patch_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -18703,7 +18707,9 @@ def test_update_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py index 6790a31c6ea0..99e163f19c61 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py @@ -3706,6 +3706,11 @@ def test_insert_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -3752,6 +3757,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py index 1ae5ba72081a..89eb8e37955c 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py @@ -21572,6 +21572,11 @@ def test_add_network_interface_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -22649,6 +22654,11 @@ def test_bulk_insert_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -22695,6 +22705,7 @@ def test_bulk_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, @@ -25184,6 +25195,11 @@ def test_insert_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -25248,6 +25264,7 @@ def test_insert_rest_call_success(request_type): "block": "block_value", "cluster": "cluster_value", "host": "host_value", + "machine": "machine_value", "subblock": "subblock_value", }, "reservation_consumption_info": { @@ -25285,6 +25302,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": {"enabled": True, "max_duration": {}}, "host_error_timeout_seconds": 2811, "instance_termination_action": "instance_termination_action_value", @@ -29546,6 +29564,7 @@ def test_set_scheduling_rest_call_success(request_type): request_init["scheduling_resource"] = { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, @@ -32324,6 +32343,11 @@ def test_update_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -32388,6 +32412,7 @@ def test_update_rest_call_success(request_type): "block": "block_value", "cluster": "cluster_value", "host": "host_value", + "machine": "machine_value", "subblock": "subblock_value", }, "reservation_consumption_info": { @@ -32425,6 +32450,7 @@ def test_update_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": {"enabled": True, "max_duration": {}}, "host_error_timeout_seconds": 2811, "instance_termination_action": "instance_termination_action_value", @@ -33225,6 +33251,11 @@ def test_update_network_interface_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py index 1ae0dcfdc099..ad312495fc87 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py @@ -4112,6 +4112,7 @@ def test_insert_rest_call_success(request_type): "location": "location_value", "macsec": { "fail_open": True, + "interconnect_key_group": "interconnect_key_group_value", "pre_shared_keys": [ {"name": "name_value", "start_time": "start_time_value"} ], @@ -4565,6 +4566,7 @@ def test_patch_rest_call_success(request_type): "location": "location_value", "macsec": { "fail_open": True, + "interconnect_key_group": "interconnect_key_group_value", "pre_shared_keys": [ {"name": "name_value", "start_time": "start_time_value"} ], diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py index b085aa11d119..e727f896f0ec 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py @@ -3659,6 +3659,11 @@ def test_insert_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -3705,6 +3710,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py index dc7298866e17..2c0a318eb042 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py @@ -4082,7 +4082,7 @@ def test_insert_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4128,7 +4128,7 @@ def test_insert_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4279,7 +4279,7 @@ def test_insert_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4325,7 +4325,7 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5562,7 +5562,7 @@ def test_patch_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5609,7 +5609,7 @@ def test_patch_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5769,7 +5769,7 @@ def test_patch_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5816,7 +5816,7 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -10668,7 +10668,7 @@ def test_update_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -10715,7 +10715,7 @@ def test_update_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -10875,7 +10875,7 @@ def test_update_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -10922,7 +10922,7 @@ def test_update_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -13481,7 +13481,9 @@ def test_insert_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2"} request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -14493,7 +14495,9 @@ def test_patch_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -18014,7 +18018,9 @@ def test_update_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py index 0f030b0f7617..b969f7acf1ff 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py @@ -2708,6 +2708,11 @@ def test_insert_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -2754,6 +2759,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py index cb9be183757d..b9fad5efca33 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py @@ -1531,6 +1531,11 @@ def test_bulk_insert_rest_call_success(request_type): ], "alias_ip_ranges": [ { + "candidate_subnetwork_range_names": [ + "candidate_subnetwork_range_names_value1", + "candidate_subnetwork_range_names_value2", + ], + "effective_subnetwork_range_name": "effective_subnetwork_range_name_value", "ip_cidr_range": "ip_cidr_range_value", "subnetwork_range_name": "subnetwork_range_name_value", } @@ -1577,6 +1582,7 @@ def test_bulk_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_ssl_policies.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_ssl_policies.py index 4583ee838982..d148df35e868 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_ssl_policies.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_ssl_policies.py @@ -1484,6 +1484,194 @@ def test_get_rest_flattened_error(transport: str = "rest"): ) +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_iam_policy_rest_required_fields( + request_type=compute.GetIamPolicyRegionSslPolicyRequest, +): + transport_class = transports.RegionSslPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("optionsRequestedPolicyVersion",)) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_iam_policy_rest_flattened(): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/regions/{region}/sslPolicies/{resource}/getIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + compute.GetIamPolicyRegionSslPolicyRequest(), + project="project_value", + region="region_value", + resource="resource_value", + ) + + def test_insert_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2697,6 +2885,198 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): ) +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_iam_policy_rest_required_fields( + request_type=compute.SetIamPolicyRegionSslPolicyRequest, +): + transport_class = transports.RegionSslPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_set_iam_policy_rest_flattened(): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + region_set_policy_request_resource=compute.RegionSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/regions/{region}/sslPolicies/{resource}/setIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + compute.SetIamPolicyRegionSslPolicyRequest(), + project="project_value", + region="region_value", + resource="resource_value", + region_set_policy_request_resource=compute.RegionSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + + def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3209,32 +3589,166 @@ def test_get_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.SslPolicy.pb(return_value) + return_value = compute.SslPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.SslPolicy) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.custom_features == ["custom_features_value"] + assert response.description == "description_value" + assert response.enabled_features == ["enabled_features_value"] + assert response.fingerprint == "fingerprint_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.min_tls_version == "min_tls_version_value" + assert response.name == "name_value" + assert response.post_quantum_key_exchange == "post_quantum_key_exchange_value" + assert response.profile == "profile_value" + assert response.region == "region_value" + assert response.self_link == "self_link_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.RegionSslPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionSslPoliciesRestInterceptor(), + ) + client = RegionSslPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.RegionSslPoliciesRestInterceptor, "post_get" + ) as post, + mock.patch.object( + transports.RegionSslPoliciesRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.RegionSslPoliciesRestInterceptor, "pre_get" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRegionSslPolicyRequest.pb( + compute.GetRegionSslPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.SslPolicy.to_json(compute.SslPolicy()) + req.return_value.content = return_value + + request = compute.GetRegionSslPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.SslPolicy() + post_with_metadata.return_value = compute.SslPolicy(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=compute.GetIamPolicyRegionSslPolicyRequest, +): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetIamPolicyRegionSslPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get(request) + response = client.get_iam_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.SslPolicy) - assert response.creation_timestamp == "creation_timestamp_value" - assert response.custom_features == ["custom_features_value"] - assert response.description == "description_value" - assert response.enabled_features == ["enabled_features_value"] - assert response.fingerprint == "fingerprint_value" - assert response.id == 205 - assert response.kind == "kind_value" - assert response.min_tls_version == "min_tls_version_value" - assert response.name == "name_value" - assert response.post_quantum_key_exchange == "post_quantum_key_exchange_value" - assert response.profile == "profile_value" - assert response.region == "region_value" - assert response.self_link == "self_link_value" + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_rest_interceptors(null_interceptor): +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.RegionSslPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3247,20 +3761,21 @@ def test_get_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.RegionSslPoliciesRestInterceptor, "post_get" + transports.RegionSslPoliciesRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( - transports.RegionSslPoliciesRestInterceptor, "post_get_with_metadata" + transports.RegionSslPoliciesRestInterceptor, + "post_get_iam_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.RegionSslPoliciesRestInterceptor, "pre_get" + transports.RegionSslPoliciesRestInterceptor, "pre_get_iam_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetRegionSslPolicyRequest.pb( - compute.GetRegionSslPolicyRequest() + pb_message = compute.GetIamPolicyRegionSslPolicyRequest.pb( + compute.GetIamPolicyRegionSslPolicyRequest() ) transcode.return_value = { "method": "post", @@ -3272,19 +3787,19 @@ def test_get_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = compute.SslPolicy.to_json(compute.SslPolicy()) + return_value = compute.Policy.to_json(compute.Policy()) req.return_value.content = return_value - request = compute.GetRegionSslPolicyRequest() + request = compute.GetIamPolicyRegionSslPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.SslPolicy() - post_with_metadata.return_value = compute.SslPolicy(), metadata + post.return_value = compute.Policy() + post_with_metadata.return_value = compute.Policy(), metadata - client.get( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -4085,6 +4600,257 @@ def test_patch_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_set_iam_policy_rest_bad_request( + request_type=compute.SetIamPolicyRegionSslPolicyRequest, +): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetIamPolicyRegionSslPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request_init["region_set_policy_request_resource"] = { + "bindings": [ + { + "binding_id": "binding_id_value", + "condition": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "members": ["members_value1", "members_value2"], + "role": "role_value", + } + ], + "etag": "etag_value", + "policy": { + "audit_configs": [ + { + "audit_log_configs": [ + { + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "ignore_child_exemptions": True, + "log_type": "log_type_value", + } + ], + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "service": "service_value", + } + ], + "bindings": {}, + "etag": "etag_value", + "iam_owned": True, + "version": 774, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetIamPolicyRegionSslPolicyRequest.meta.fields[ + "region_set_policy_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "region_set_policy_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["region_set_policy_request_resource"][field]) + ): + del request_init["region_set_policy_request_resource"][field][i][ + subfield + ] + else: + del request_init["region_set_policy_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.RegionSslPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionSslPoliciesRestInterceptor(), + ) + client = RegionSslPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.RegionSslPoliciesRestInterceptor, "post_set_iam_policy" + ) as post, + mock.patch.object( + transports.RegionSslPoliciesRestInterceptor, + "post_set_iam_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.RegionSslPoliciesRestInterceptor, "pre_set_iam_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.SetIamPolicyRegionSslPolicyRequest.pb( + compute.SetIamPolicyRegionSslPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Policy.to_json(compute.Policy()) + req.return_value.content = return_value + + request = compute.SetIamPolicyRegionSslPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Policy() + post_with_metadata.return_value = compute.Policy(), metadata + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_test_iam_permissions_rest_bad_request( request_type=compute.TestIamPermissionsRegionSslPolicyRequest, ): @@ -4341,6 +5107,25 @@ def test_get_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetIamPolicyRegionSslPolicyRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_insert_unary_empty_call_rest(): @@ -4419,6 +5204,25 @@ def test_patch_unary_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = RegionSslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.SetIamPolicyRegionSslPolicyRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_test_iam_permissions_empty_call_rest(): @@ -4464,10 +5268,12 @@ def test_region_ssl_policies_base_transport(): methods = ( "delete", "get", + "get_iam_policy", "insert", "list", "list_available_features", "patch", + "set_iam_policy", "test_iam_permissions", ) for method in methods: @@ -4618,6 +5424,9 @@ def test_region_ssl_policies_client_transport_session_collision(transport_name): session1 = client1.transport.get._session session2 = client2.transport.get._session assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 session1 = client1.transport.insert._session session2 = client2.transport.insert._session assert session1 != session2 @@ -4630,6 +5439,9 @@ def test_region_ssl_policies_client_transport_session_collision(transport_name): session1 = client1.transport.patch._session session2 = client2.transport.patch._session assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 session1 = client1.transport.test_iam_permissions._session session2 = client2.transport.test_iam_permissions._session assert session1 != session2 diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py index 88bef1565199..9b737f1a0706 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py @@ -4159,6 +4159,9 @@ def test_insert_rest_call_success(request_type): "expose_headers": ["expose_headers_value1", "expose_headers_value2"], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, @@ -5015,6 +5018,9 @@ def test_patch_rest_call_success(request_type): "expose_headers": ["expose_headers_value1", "expose_headers_value2"], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, @@ -5699,6 +5705,9 @@ def test_update_rest_call_success(request_type): "expose_headers": ["expose_headers_value1", "expose_headers_value2"], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, @@ -6176,6 +6185,9 @@ def test_validate_rest_call_success(request_type): ], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_ssl_policies.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_ssl_policies.py index 70f20af1ddb5..0f28b1afb3aa 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_ssl_policies.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_ssl_policies.py @@ -1687,6 +1687,184 @@ def test_get_rest_flattened_error(transport: str = "rest"): ) +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_iam_policy_rest_required_fields( + request_type=compute.GetIamPolicySslPolicyRequest, +): + transport_class = transports.SslPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("optionsRequestedPolicyVersion",)) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_iam_policy_rest_flattened(): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "resource": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/global/sslPolicies/{resource}/getIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + compute.GetIamPolicySslPolicyRequest(), + project="project_value", + resource="resource_value", + ) + + def test_insert_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2852,6 +3030,188 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): ) +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_iam_policy_rest_required_fields( + request_type=compute.SetIamPolicySslPolicyRequest, +): + transport_class = transports.SslPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_set_iam_policy_rest_flattened(): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "resource": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + resource="resource_value", + global_set_policy_request_resource=compute.GlobalSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/global/sslPolicies/{resource}/setIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + compute.SetIamPolicySslPolicyRequest(), + project="project_value", + resource="resource_value", + global_set_policy_request_resource=compute.GlobalSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + + def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3490,32 +3850,160 @@ def test_get_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.SslPolicy.pb(return_value) + return_value = compute.SslPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.SslPolicy) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.custom_features == ["custom_features_value"] + assert response.description == "description_value" + assert response.enabled_features == ["enabled_features_value"] + assert response.fingerprint == "fingerprint_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.min_tls_version == "min_tls_version_value" + assert response.name == "name_value" + assert response.post_quantum_key_exchange == "post_quantum_key_exchange_value" + assert response.profile == "profile_value" + assert response.region == "region_value" + assert response.self_link == "self_link_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.SslPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SslPoliciesRestInterceptor(), + ) + client = SslPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.SslPoliciesRestInterceptor, "post_get") as post, + mock.patch.object( + transports.SslPoliciesRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.SslPoliciesRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetSslPolicyRequest.pb(compute.GetSslPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.SslPolicy.to_json(compute.SslPolicy()) + req.return_value.content = return_value + + request = compute.GetSslPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.SslPolicy() + post_with_metadata.return_value = compute.SslPolicy(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=compute.GetIamPolicySslPolicyRequest, +): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "resource": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetIamPolicySslPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "resource": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get(request) + response = client.get_iam_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.SslPolicy) - assert response.creation_timestamp == "creation_timestamp_value" - assert response.custom_features == ["custom_features_value"] - assert response.description == "description_value" - assert response.enabled_features == ["enabled_features_value"] - assert response.fingerprint == "fingerprint_value" - assert response.id == 205 - assert response.kind == "kind_value" - assert response.min_tls_version == "min_tls_version_value" - assert response.name == "name_value" - assert response.post_quantum_key_exchange == "post_quantum_key_exchange_value" - assert response.profile == "profile_value" - assert response.region == "region_value" - assert response.self_link == "self_link_value" + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_rest_interceptors(null_interceptor): +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.SslPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3527,16 +4015,22 @@ def test_get_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.SslPoliciesRestInterceptor, "post_get") as post, mock.patch.object( - transports.SslPoliciesRestInterceptor, "post_get_with_metadata" + transports.SslPoliciesRestInterceptor, "post_get_iam_policy" + ) as post, + mock.patch.object( + transports.SslPoliciesRestInterceptor, "post_get_iam_policy_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.SslPoliciesRestInterceptor, "pre_get") as pre, + mock.patch.object( + transports.SslPoliciesRestInterceptor, "pre_get_iam_policy" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetSslPolicyRequest.pb(compute.GetSslPolicyRequest()) + pb_message = compute.GetIamPolicySslPolicyRequest.pb( + compute.GetIamPolicySslPolicyRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3547,19 +4041,19 @@ def test_get_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = compute.SslPolicy.to_json(compute.SslPolicy()) + return_value = compute.Policy.to_json(compute.Policy()) req.return_value.content = return_value - request = compute.GetSslPolicyRequest() + request = compute.GetIamPolicySslPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.SslPolicy() - post_with_metadata.return_value = compute.SslPolicy(), metadata + post.return_value = compute.Policy() + post_with_metadata.return_value = compute.Policy(), metadata - client.get( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -4342,6 +4836,256 @@ def test_patch_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_set_iam_policy_rest_bad_request( + request_type=compute.SetIamPolicySslPolicyRequest, +): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "resource": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetIamPolicySslPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "resource": "sample2"} + request_init["global_set_policy_request_resource"] = { + "bindings": [ + { + "binding_id": "binding_id_value", + "condition": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "members": ["members_value1", "members_value2"], + "role": "role_value", + } + ], + "etag": "etag_value", + "policy": { + "audit_configs": [ + { + "audit_log_configs": [ + { + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "ignore_child_exemptions": True, + "log_type": "log_type_value", + } + ], + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "service": "service_value", + } + ], + "bindings": {}, + "etag": "etag_value", + "iam_owned": True, + "version": 774, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetIamPolicySslPolicyRequest.meta.fields[ + "global_set_policy_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "global_set_policy_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["global_set_policy_request_resource"][field]) + ): + del request_init["global_set_policy_request_resource"][field][i][ + subfield + ] + else: + del request_init["global_set_policy_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SslPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SslPoliciesRestInterceptor(), + ) + client = SslPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SslPoliciesRestInterceptor, "post_set_iam_policy" + ) as post, + mock.patch.object( + transports.SslPoliciesRestInterceptor, "post_set_iam_policy_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.SslPoliciesRestInterceptor, "pre_set_iam_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.SetIamPolicySslPolicyRequest.pb( + compute.SetIamPolicySslPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Policy.to_json(compute.Policy()) + req.return_value.content = return_value + + request = compute.SetIamPolicySslPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Policy() + post_with_metadata.return_value = compute.Policy(), metadata + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_test_iam_permissions_rest_bad_request( request_type=compute.TestIamPermissionsSslPolicyRequest, ): @@ -4617,6 +5361,25 @@ def test_get_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetIamPolicySslPolicyRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_insert_unary_empty_call_rest(): @@ -4695,6 +5458,25 @@ def test_patch_unary_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = SslPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.SetIamPolicySslPolicyRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_test_iam_permissions_empty_call_rest(): @@ -4741,10 +5523,12 @@ def test_ssl_policies_base_transport(): "aggregated_list", "delete", "get", + "get_iam_policy", "insert", "list", "list_available_features", "patch", + "set_iam_policy", "test_iam_permissions", ) for method in methods: @@ -4898,6 +5682,9 @@ def test_ssl_policies_client_transport_session_collision(transport_name): session1 = client1.transport.get._session session2 = client2.transport.get._session assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 session1 = client1.transport.insert._session session2 = client2.transport.insert._session assert session1 != session2 @@ -4910,6 +5697,9 @@ def test_ssl_policies_client_transport_session_collision(transport_name): session1 = client1.transport.patch._session session2 = client2.transport.patch._session assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 session1 = client1.transport.test_iam_permissions._session session2 = client2.transport.test_iam_permissions._session assert session1 != session2 diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py index 9840ed11ea9e..7d80eb4eef2f 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py @@ -4399,6 +4399,9 @@ def test_insert_rest_call_success(request_type): "expose_headers": ["expose_headers_value1", "expose_headers_value2"], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, @@ -5242,6 +5245,9 @@ def test_patch_rest_call_success(request_type): "expose_headers": ["expose_headers_value1", "expose_headers_value2"], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, @@ -5917,6 +5923,9 @@ def test_update_rest_call_success(request_type): "expose_headers": ["expose_headers_value1", "expose_headers_value2"], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, @@ -6392,6 +6401,9 @@ def test_validate_rest_call_success(request_type): ], "max_age": 722, }, + "dynamic_compression_policy": { + "compression_mode": "compression_mode_value" + }, "fault_injection_policy": { "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, diff --git a/packages/google-cloud-compute/CHANGELOG.md b/packages/google-cloud-compute/CHANGELOG.md index ade9f7a7193f..06c05c7133c8 100644 --- a/packages/google-cloud-compute/CHANGELOG.md +++ b/packages/google-cloud-compute/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-compute/#history +## [1.54.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1.53.0...google-cloud-compute-v1.54.0) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [1.53.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1.52.0...google-cloud-compute-v1.53.0) (2026-09-14) diff --git a/packages/google-cloud-compute/docs/compute_v1/project_views.rst b/packages/google-cloud-compute/docs/compute_v1/project_views.rst new file mode 100644 index 000000000000..fd564cefcb85 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/project_views.rst @@ -0,0 +1,6 @@ +ProjectViews +------------------------------ + +.. automodule:: google.cloud.compute_v1.services.project_views + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/services_.rst b/packages/google-cloud-compute/docs/compute_v1/services_.rst index 8aa28091777e..928851b02ee5 100644 --- a/packages/google-cloud-compute/docs/compute_v1/services_.rst +++ b/packages/google-cloud-compute/docs/compute_v1/services_.rst @@ -59,6 +59,7 @@ Services for Google Cloud Compute v1 API packet_mirrorings preview_features projects + project_views public_advertised_prefixes public_delegated_prefixes region_autoscalers diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index 027dd842c37a..c70c8c6e9788 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -141,6 +141,7 @@ from google.cloud.compute_v1.services.preview_features.client import ( PreviewFeaturesClient, ) +from google.cloud.compute_v1.services.project_views.client import ProjectViewsClient from google.cloud.compute_v1.services.projects.client import ProjectsClient from google.cloud.compute_v1.services.public_advertised_prefixes.client import ( PublicAdvertisedPrefixesClient, @@ -517,6 +518,27 @@ CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, + CapacityAdviceRequest, + CapacityAdviceRequestDistributionPolicy, + CapacityAdviceRequestDistributionPolicyZoneConfiguration, + CapacityAdviceRequestInstanceFlexibilityPolicy, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk, + CapacityAdviceRequestInstanceProperties, + CapacityAdviceRequestInstancePropertiesScheduling, + CapacityAdviceResponse, + CapacityAdviceResponseRecommendation, + CapacityAdviceResponseRecommendationScores, + CapacityAdviceResponseRecommendationShard, + CapacityAdviceRpcRequest, + CapacityHistoryAdviceRequest, + CapacityHistoryRequest, + CapacityHistoryRequestInstanceProperties, + CapacityHistoryRequestInstancePropertiesScheduling, + CapacityHistoryRequestLocationPolicy, + CapacityHistoryResponse, + CapacityHistoryResponsePreemptionRecord, + CapacityHistoryResponsePriceRecord, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -875,6 +897,7 @@ GetPacketMirroringRuleNetworkFirewallPolicyRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -1310,6 +1333,7 @@ InterconnectRemoteLocationPermittedConnections, InterconnectsGetDiagnosticsResponse, InterconnectsGetMacsecConfigResponse, + Interval, InvalidateCacheUrlMapRequest, Items, License, @@ -1490,6 +1514,7 @@ Metadata, MetadataFilter, MetadataFilterLabelMatch, + Money, MoveAddressRequest, MoveDiskProjectRequest, MoveFirewallPolicyRequest, @@ -1685,6 +1710,7 @@ ProjectsListXpnHostsRequest, ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -2415,6 +2441,7 @@ "PacketMirroringsClient", "PreviewFeaturesClient", "ProjectsClient", + "ProjectViewsClient", "PublicAdvertisedPrefixesClient", "PublicDelegatedPrefixesClient", "RegionAutoscalersClient", @@ -2691,6 +2718,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -3049,6 +3097,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -3484,6 +3533,7 @@ "InterconnectRemoteLocationPermittedConnections", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -3664,6 +3714,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -3859,6 +3910,7 @@ "ProjectsListXpnHostsRequest", "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", + "ProjectView", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", "PublicAdvertisedPrefixPublicDelegatedPrefix", diff --git a/packages/google-cloud-compute/google/cloud/compute/gapic_version.py b/packages/google-cloud-compute/google/cloud/compute/gapic_version.py index 0b6f44127d9c..aed3c7768b55 100644 --- a/packages/google-cloud-compute/google/cloud/compute/gapic_version.py +++ b/packages/google-cloud-compute/google/cloud/compute/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.53.0" # {x-release-please-version} +__version__ = "1.54.0" # {x-release-please-version} diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 05f5fc39f3a1..56ed0733a80a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -81,6 +81,7 @@ "google.cloud.compute_v1.services.organization_security_policies", "google.cloud.compute_v1.services.packet_mirrorings", "google.cloud.compute_v1.services.preview_features", + "google.cloud.compute_v1.services.project_views", "google.cloud.compute_v1.services.projects", "google.cloud.compute_v1.services.public_advertised_prefixes", "google.cloud.compute_v1.services.public_delegated_prefixes", @@ -214,6 +215,7 @@ from .services.organization_security_policies import OrganizationSecurityPoliciesClient from .services.packet_mirrorings import PacketMirroringsClient from .services.preview_features import PreviewFeaturesClient +from .services.project_views import ProjectViewsClient from .services.projects import ProjectsClient from .services.public_advertised_prefixes import PublicAdvertisedPrefixesClient from .services.public_delegated_prefixes import PublicDelegatedPrefixesClient @@ -498,6 +500,27 @@ CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, + CapacityAdviceRequest, + CapacityAdviceRequestDistributionPolicy, + CapacityAdviceRequestDistributionPolicyZoneConfiguration, + CapacityAdviceRequestInstanceFlexibilityPolicy, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk, + CapacityAdviceRequestInstanceProperties, + CapacityAdviceRequestInstancePropertiesScheduling, + CapacityAdviceResponse, + CapacityAdviceResponseRecommendation, + CapacityAdviceResponseRecommendationScores, + CapacityAdviceResponseRecommendationShard, + CapacityAdviceRpcRequest, + CapacityHistoryAdviceRequest, + CapacityHistoryRequest, + CapacityHistoryRequestInstanceProperties, + CapacityHistoryRequestInstancePropertiesScheduling, + CapacityHistoryRequestLocationPolicy, + CapacityHistoryResponse, + CapacityHistoryResponsePreemptionRecord, + CapacityHistoryResponsePriceRecord, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -856,6 +879,7 @@ GetPacketMirroringRuleNetworkFirewallPolicyRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -1291,6 +1315,7 @@ InterconnectRemoteLocationPermittedConnections, InterconnectsGetDiagnosticsResponse, InterconnectsGetMacsecConfigResponse, + Interval, InvalidateCacheUrlMapRequest, Items, License, @@ -1471,6 +1496,7 @@ Metadata, MetadataFilter, MetadataFilterLabelMatch, + Money, MoveAddressRequest, MoveDiskProjectRequest, MoveFirewallPolicyRequest, @@ -1666,6 +1692,7 @@ ProjectsListXpnHostsRequest, ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -2553,6 +2580,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -2921,6 +2969,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -3379,6 +3428,7 @@ "InterconnectsClient", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -3563,6 +3613,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -3764,6 +3815,8 @@ "PreviewFeaturesClient", "PreviewRouterRequest", "Project", + "ProjectView", + "ProjectViewsClient", "ProjectsClient", "ProjectsDisableXpnResourceRequest", "ProjectsEnableXpnResourceRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json index 3d690307220f..85d4758279d6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json @@ -87,6 +87,16 @@ "methods": [ "calendar_mode" ] + }, + "Capacity": { + "methods": [ + "capacity" + ] + }, + "CapacityHistory": { + "methods": [ + "capacity_history" + ] } } } @@ -2880,6 +2890,20 @@ } } }, + "ProjectViews": { + "clients": { + "rest": { + "libraryClient": "ProjectViewsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + } + } + } + } + }, "Projects": { "clients": { "rest": { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py index 0b6f44127d9c..aed3c7768b55 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.53.0" # {x-release-please-version} +__version__ = "1.54.0" # {x-release-please-version} diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py index 0b93d44c67cc..74f0493fad1b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py @@ -707,6 +707,272 @@ def sample_calendar_mode(): # Done; return the response. return response + def capacity( + self, + request: Optional[Union[compute.CapacityAdviceRpcRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + capacity_advice_request_resource: Optional[ + compute.CapacityAdviceRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityAdviceResponse: + r"""Advice on making real-time decisions (such as + choosing zone or machine types) during deployment to + maximize your chances of obtaining capacity. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_capacity(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityAdviceRpcRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CapacityAdviceRpcRequest, dict]): + The request object. A request message for + Advice.Capacity. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + capacity_advice_request_resource (google.cloud.compute_v1.types.CapacityAdviceRequest): + The body resource for this request + This corresponds to the ``capacity_advice_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.CapacityAdviceResponse: + A response contains scoring + recommendations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, region, capacity_advice_request_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CapacityAdviceRpcRequest): + request = compute.CapacityAdviceRpcRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if capacity_advice_request_resource is not None: + request.capacity_advice_request_resource = ( + capacity_advice_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.capacity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def capacity_history( + self, + request: Optional[Union[compute.CapacityHistoryAdviceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + capacity_history_request_resource: Optional[ + compute.CapacityHistoryRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityHistoryResponse: + r"""Gets the capacity history. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_capacity_history(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityHistoryAdviceRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity_history(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CapacityHistoryAdviceRequest, dict]): + The request object. A request message for + Advice.CapacityHistory. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + capacity_history_request_resource (google.cloud.compute_v1.types.CapacityHistoryRequest): + The body resource for this request + This corresponds to the ``capacity_history_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.CapacityHistoryResponse: + Contains the capacity history. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, region, capacity_history_request_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CapacityHistoryAdviceRequest): + request = compute.CapacityHistoryAdviceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if capacity_history_request_resource is not None: + request.capacity_history_request_resource = ( + capacity_history_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.capacity_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "AdviceClient": return self diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py index e4572717cb0b..d4e15a35b9da 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py @@ -148,6 +148,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.capacity: gapic_v1.method.wrap_method( + self.capacity, + default_timeout=600.0, + client_info=client_info, + ), + self.capacity_history: gapic_v1.method.wrap_method( + self.capacity_history, + default_timeout=600.0, + client_info=client_info, + ), } def close(self): @@ -171,6 +181,28 @@ def calendar_mode( ]: raise NotImplementedError() + @property + def capacity( + self, + ) -> Callable[ + [compute.CapacityAdviceRpcRequest], + Union[ + compute.CapacityAdviceResponse, Awaitable[compute.CapacityAdviceResponse] + ], + ]: + raise NotImplementedError() + + @property + def capacity_history( + self, + ) -> Callable[ + [compute.CapacityHistoryAdviceRequest], + Union[ + compute.CapacityHistoryResponse, Awaitable[compute.CapacityHistoryResponse] + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py index 5f6f1c2c010e..1c14e9771201 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py @@ -80,6 +80,22 @@ def post_calendar_mode(self, response): logging.log(f"Received response: {response}") return response + def pre_capacity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_capacity(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_capacity_history(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_capacity_history(self, response): + logging.log(f"Received response: {response}") + return response + transport = AdviceRestTransport(interceptor=MyCustomAdviceInterceptor()) client = AdviceClient(transport=transport) @@ -136,6 +152,104 @@ def post_calendar_mode_with_metadata( """ return response, metadata + def pre_capacity( + self, + request: compute.CapacityAdviceRpcRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CapacityAdviceRpcRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for capacity + + Override in a subclass to manipulate the request or metadata + before they are sent to the Advice server. + """ + return request, metadata + + def post_capacity( + self, response: compute.CapacityAdviceResponse + ) -> compute.CapacityAdviceResponse: + """Post-rpc interceptor for capacity + + DEPRECATED. Please use the `post_capacity_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Advice server but before + it is returned to user code. This `post_capacity` interceptor runs + before the `post_capacity_with_metadata` interceptor. + """ + return response + + def post_capacity_with_metadata( + self, + response: compute.CapacityAdviceResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.CapacityAdviceResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for capacity + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Advice server but before it is returned to user code. + + We recommend only using this `post_capacity_with_metadata` + interceptor in new development instead of the `post_capacity` interceptor. + When both interceptors are used, this `post_capacity_with_metadata` interceptor runs after the + `post_capacity` interceptor. The (possibly modified) response returned by + `post_capacity` will be passed to + `post_capacity_with_metadata`. + """ + return response, metadata + + def pre_capacity_history( + self, + request: compute.CapacityHistoryAdviceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CapacityHistoryAdviceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for capacity_history + + Override in a subclass to manipulate the request or metadata + before they are sent to the Advice server. + """ + return request, metadata + + def post_capacity_history( + self, response: compute.CapacityHistoryResponse + ) -> compute.CapacityHistoryResponse: + """Post-rpc interceptor for capacity_history + + DEPRECATED. Please use the `post_capacity_history_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Advice server but before + it is returned to user code. This `post_capacity_history` interceptor runs + before the `post_capacity_history_with_metadata` interceptor. + """ + return response + + def post_capacity_history_with_metadata( + self, + response: compute.CapacityHistoryResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CapacityHistoryResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for capacity_history + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Advice server but before it is returned to user code. + + We recommend only using this `post_capacity_history_with_metadata` + interceptor in new development instead of the `post_capacity_history` interceptor. + When both interceptors are used, this `post_capacity_history_with_metadata` interceptor runs after the + `post_capacity_history` interceptor. The (possibly modified) response returned by + `post_capacity_history` will be passed to + `post_capacity_history_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class AdviceRestStub: @@ -389,6 +503,304 @@ def __call__( ) return resp + class _Capacity(_BaseAdviceRestTransport._BaseCapacity, AdviceRestStub): + def __hash__(self): + return hash("AdviceRestTransport.Capacity") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.CapacityAdviceRpcRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityAdviceResponse: + r"""Call the capacity method over HTTP. + + Args: + request (~.compute.CapacityAdviceRpcRequest): + The request object. A request message for + Advice.Capacity. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.CapacityAdviceResponse: + A response contains scoring + recommendations. + + """ + + http_options = _BaseAdviceRestTransport._BaseCapacity._get_http_options() + request, metadata = self._interceptor.pre_capacity(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAdviceRestTransport._BaseCapacity, + "_BaseCapacity__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.AdviceClient.Capacity", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "Capacity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdviceRestTransport._Capacity._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.CapacityAdviceResponse() + pb_resp = compute.CapacityAdviceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_capacity(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_capacity_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.CapacityAdviceResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.AdviceClient.capacity", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "Capacity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CapacityHistory( + _BaseAdviceRestTransport._BaseCapacityHistory, AdviceRestStub + ): + def __hash__(self): + return hash("AdviceRestTransport.CapacityHistory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.CapacityHistoryAdviceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityHistoryResponse: + r"""Call the capacity history method over HTTP. + + Args: + request (~.compute.CapacityHistoryAdviceRequest): + The request object. A request message for + Advice.CapacityHistory. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.CapacityHistoryResponse: + Contains the capacity history. + """ + + http_options = ( + _BaseAdviceRestTransport._BaseCapacityHistory._get_http_options() + ) + request, metadata = self._interceptor.pre_capacity_history( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAdviceRestTransport._BaseCapacityHistory, + "_BaseCapacityHistory__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.AdviceClient.CapacityHistory", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "CapacityHistory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdviceRestTransport._CapacityHistory._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.CapacityHistoryResponse() + pb_resp = compute.CapacityHistoryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_capacity_history(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_capacity_history_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.CapacityHistoryResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.AdviceClient.capacity_history", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "CapacityHistory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def calendar_mode( self, @@ -399,6 +811,24 @@ def calendar_mode( # In C++ this would require a dynamic_cast return self._CalendarMode(self._session, self._host, self._interceptor) # type: ignore + @property + def capacity( + self, + ) -> Callable[[compute.CapacityAdviceRpcRequest], compute.CapacityAdviceResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Capacity(self._session, self._host, self._interceptor) # type: ignore + + @property + def capacity_history( + self, + ) -> Callable[ + [compute.CapacityHistoryAdviceRequest], compute.CapacityHistoryResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CapacityHistory(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py index 8f470cba5b2c..158fe0974650 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py @@ -104,5 +104,39 @@ def _get_http_options(): ] return http_options + class _BaseCapacity: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/advice/capacity", + "body": "capacity_advice_request_resource", + }, + ] + return http_options + + class _BaseCapacityHistory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/advice/capacityHistory", + "body": "capacity_history_request_resource", + }, + ] + return http_options + __all__ = ("_BaseAdviceRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/__init__.py new file mode 100644 index 000000000000..6be82c91e927 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProjectViewsClient + +__all__ = ("ProjectViewsClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/client.py new file mode 100644 index 000000000000..e8b9f2faf1ac --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/client.py @@ -0,0 +1,723 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, ProjectViewsTransport +from .transports.rest import ProjectViewsRestTransport + + +class ProjectViewsClientMeta(type): + """Metaclass for the ProjectViews client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ProjectViewsTransport]] + _transport_registry["rest"] = ProjectViewsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ProjectViewsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ProjectViewsClient(metaclass=ProjectViewsClientMeta): + """The ProjectViews API.""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProjectViewsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProjectViewsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ProjectViewsTransport: + """Returns the transport used by the client instance. + + Returns: + ProjectViewsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ProjectViewsTransport, Callable[..., ProjectViewsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the project views client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ProjectViewsTransport,Callable[..., ProjectViewsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ProjectViewsTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = ProjectViewsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=ProjectViewsClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ProjectViewsTransport) + if transport_provided: + # transport is a ProjectViewsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(ProjectViewsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=ProjectViewsClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=ProjectViewsClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[ProjectViewsTransport], Callable[..., ProjectViewsTransport] + ] = ( + ProjectViewsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ProjectViewsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.compute_v1.ProjectViewsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1.ProjectViews", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.compute.v1.ProjectViews", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetProjectViewRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ProjectView: + r"""Returns the specified global ProjectViews resource, with a + regional context. This regional API endpoint reads resource + metadata from regional read-only replicas. Because changes are + copied to these regional replicas asynchronously, for real-time + resource reads or any write operations (creating, updating, or + deleting resources), use the global + `projects.get `__ + endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get(): + # Create a client + client = compute_v1.ProjectViewsClient() + + # Initialize request argument(s) + request = compute_v1.GetProjectViewRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetProjectViewRequest, dict]): + The request object. A request message for + ProjectViews.Get. See the method + description for details. + project (str): + Required. Project ID for this + request. This is part of the URL path. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Required. Name of the region for this + request. This is part of the URL path. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.ProjectView: + Represents a ProjectView resource. + + A ProjectView resource contains + read-only project data which is + available globally. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, region] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetProjectViewRequest): + request = compute.GetProjectViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ProjectViewsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ProjectViewsClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/README.rst b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/README.rst new file mode 100644 index 000000000000..fb7baaad14ee --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``ProjectViewsTransport`` is the ABC for all transports. + +- public child ``ProjectViewsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``ProjectViewsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseProjectViewsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``ProjectViewsRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/__init__.py new file mode 100644 index 000000000000..9dcc22fc47ec --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ProjectViewsTransport +from .rest import ProjectViewsRestInterceptor, ProjectViewsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProjectViewsTransport]] +_transport_registry["rest"] = ProjectViewsRestTransport + +__all__ = ( + "ProjectViewsTransport", + "ProjectViewsRestTransport", + "ProjectViewsRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/base.py new file mode 100644 index 000000000000..7442b65c0203 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/base.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ProjectViewsTransport(abc.ABC): + """Abstract transport class for ProjectViews.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetProjectViewRequest], + Union[compute.ProjectView, Awaitable[compute.ProjectView]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ProjectViewsTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest.py new file mode 100644 index 000000000000..2445e6ddc8d9 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1._compat import transcode_request +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProjectViewsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ProjectViewsRestInterceptor: + """Interceptor for ProjectViews. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ProjectViewsRestTransport. + + .. code-block:: python + class MyCustomProjectViewsInterceptor(ProjectViewsRestInterceptor): + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProjectViewsRestTransport(interceptor=MyCustomProjectViewsInterceptor()) + client = ProjectViewsClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetProjectViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetProjectViewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProjectViews server. + """ + return request, metadata + + def post_get(self, response: compute.ProjectView) -> compute.ProjectView: + """Post-rpc interceptor for get + + DEPRECATED. Please use the `post_get_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProjectViews server but before + it is returned to user code. This `post_get` interceptor runs + before the `post_get_with_metadata` interceptor. + """ + return response + + def post_get_with_metadata( + self, + response: compute.ProjectView, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ProjectView, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProjectViews server but before it is returned to user code. + + We recommend only using this `post_get_with_metadata` + interceptor in new development instead of the `post_get` interceptor. + When both interceptors are used, this `post_get_with_metadata` interceptor runs after the + `post_get` interceptor. The (possibly modified) response returned by + `post_get` will be passed to + `post_get_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ProjectViewsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProjectViewsRestInterceptor + + +class ProjectViewsRestTransport(_BaseProjectViewsRestTransport): + """REST backend synchronous transport for ProjectViews. + + The ProjectViews API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ProjectViewsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[ProjectViewsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ProjectViewsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BaseProjectViewsRestTransport._BaseGet, ProjectViewsRestStub): + def __hash__(self): + return hash("ProjectViewsRestTransport.Get") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetProjectViewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ProjectView: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetProjectViewRequest): + The request object. A request message for + ProjectViews.Get. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.ProjectView: + Represents a ProjectView resource. + + A ProjectView resource contains + read-only project data which is + available globally. + + """ + + http_options = _BaseProjectViewsRestTransport._BaseGet._get_http_options() + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseProjectViewsRestTransport._BaseGet, + "_BaseGet__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.ProjectViewsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1.ProjectViews", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProjectViewsRestTransport._Get._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.ProjectView() + pb_resp = compute.ProjectView.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.ProjectView.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.ProjectViewsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1.ProjectViews", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get(self) -> Callable[[compute.GetProjectViewRequest], compute.ProjectView]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ProjectViewsRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest_base.py new file mode 100644 index 000000000000..12259bfb076c --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest_base.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO, ProjectViewsTransport + + +class _BaseProjectViewsRestTransport(ProjectViewsTransport): + """Base REST backend transport for ProjectViews. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/regions/{region}/projectViews", + }, + ] + return http_options + + +__all__ = ("_BaseProjectViewsRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py index 6d4b6c14d354..7e744dbe7af6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py @@ -221,6 +221,27 @@ CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, + CapacityAdviceRequest, + CapacityAdviceRequestDistributionPolicy, + CapacityAdviceRequestDistributionPolicyZoneConfiguration, + CapacityAdviceRequestInstanceFlexibilityPolicy, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk, + CapacityAdviceRequestInstanceProperties, + CapacityAdviceRequestInstancePropertiesScheduling, + CapacityAdviceResponse, + CapacityAdviceResponseRecommendation, + CapacityAdviceResponseRecommendationScores, + CapacityAdviceResponseRecommendationShard, + CapacityAdviceRpcRequest, + CapacityHistoryAdviceRequest, + CapacityHistoryRequest, + CapacityHistoryRequestInstanceProperties, + CapacityHistoryRequestInstancePropertiesScheduling, + CapacityHistoryRequestLocationPolicy, + CapacityHistoryResponse, + CapacityHistoryResponsePreemptionRecord, + CapacityHistoryResponsePriceRecord, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -579,6 +600,7 @@ GetPacketMirroringRuleNetworkFirewallPolicyRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -1014,6 +1036,7 @@ InterconnectRemoteLocationPermittedConnections, InterconnectsGetDiagnosticsResponse, InterconnectsGetMacsecConfigResponse, + Interval, InvalidateCacheUrlMapRequest, Items, License, @@ -1194,6 +1217,7 @@ Metadata, MetadataFilter, MetadataFilterLabelMatch, + Money, MoveAddressRequest, MoveDiskProjectRequest, MoveFirewallPolicyRequest, @@ -1389,6 +1413,7 @@ ProjectsListXpnHostsRequest, ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -2270,6 +2295,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -2628,6 +2674,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -3063,6 +3110,7 @@ "InterconnectRemoteLocationPermittedConnections", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -3243,6 +3291,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -3438,6 +3487,7 @@ "ProjectsListXpnHostsRequest", "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", + "ProjectView", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", "PublicAdvertisedPrefixPublicDelegatedPrefix", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py index 102ab92b9953..053b37f4b9c4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py @@ -230,6 +230,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -590,6 +611,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -1023,6 +1045,7 @@ "InterconnectRemoteLocationPermittedConnections", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -1203,6 +1226,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -1392,6 +1416,7 @@ "PreviewFeatureStatusReleaseStatus", "PreviewRouterRequest", "Project", + "ProjectView", "ProjectsDisableXpnResourceRequest", "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", @@ -22272,10 +22297,11 @@ class BackendServiceHAPolicyLeaderNetworkEndpoint(proto.Message): attached to the NEG specified in the haPolicy.leader.backendGroup. - The name must be 1-63 characters long, and - comply with RFC1035. Authorization requires the - following IAM permission on the specified - resource instance: compute.instances.use + The value must be a valid RFC1035 name (1-63 + characters) or a valid instance URL. + Authorization requires the following IAM + permission on the specified resource instance: + compute.instances.use This field is a member of `oneof`_ ``_instance``. """ @@ -25679,6 +25705,819 @@ class CancelRolloutRequest(proto.Message): ) +class CapacityAdviceRequest(proto.Message): + r"""A request to provide Assistant Scores. These scores determine + VM obtainability and preemption likelihood. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + distribution_policy (google.cloud.compute_v1.types.CapacityAdviceRequestDistributionPolicy): + Policy specifying the distribution of + instances across zones within the requested + region. + + This field is a member of `oneof`_ ``_distribution_policy``. + instance_flexibility_policy (google.cloud.compute_v1.types.CapacityAdviceRequestInstanceFlexibilityPolicy): + Policy for instance selectors. + + This field is a member of `oneof`_ ``_instance_flexibility_policy``. + instance_properties (google.cloud.compute_v1.types.CapacityAdviceRequestInstanceProperties): + Instance properties for this request. + + This field is a member of `oneof`_ ``_instance_properties``. + size (int): + The number of VM instances to request. + + This field is a member of `oneof`_ ``_size``. + """ + + distribution_policy: "CapacityAdviceRequestDistributionPolicy" = proto.Field( + proto.MESSAGE, + number=534558541, + optional=True, + message="CapacityAdviceRequestDistributionPolicy", + ) + instance_flexibility_policy: "CapacityAdviceRequestInstanceFlexibilityPolicy" = ( + proto.Field( + proto.MESSAGE, + number=26937090, + optional=True, + message="CapacityAdviceRequestInstanceFlexibilityPolicy", + ) + ) + instance_properties: "CapacityAdviceRequestInstanceProperties" = proto.Field( + proto.MESSAGE, + number=215355165, + optional=True, + message="CapacityAdviceRequestInstanceProperties", + ) + size: int = proto.Field( + proto.INT32, + number=3530753, + optional=True, + ) + + +class CapacityAdviceRequestDistributionPolicy(proto.Message): + r"""Distribution policy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + target_shape (str): + Target distribution shape. You can specify the following + values:ANY, ANY_SINGLE_ZONE, or BALANCED. Check the + TargetShape enum for the list of possible values. + + This field is a member of `oneof`_ ``_target_shape``. + zones (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceRequestDistributionPolicyZoneConfiguration]): + Zones where Capacity Advisor looks for + capacity. + """ + + class TargetShape(proto.Enum): + r"""Target distribution shape. You can specify the following values:ANY, + ANY_SINGLE_ZONE, or BALANCED. + + Values: + UNDEFINED_TARGET_SHAPE (0): + A value indicating that the enum field is not + set. + ANY (64972): + Picks zones for creating VM instances to + fulfill the requested number of VMs within + present resource constraints. + ANY_SINGLE_ZONE (61100880): + Creates all VM instances within a single + zone. The zone is selected based on the present + resource constraints. + BALANCED (468409608): + Prioritizes acquisition of resources, + scheduling VMs in zones where resources are + available while distributing VMs as evenly as + possible across selected zones to minimize the + impact of zonal failure. + TARGET_SHAPE_UNSPECIFIED (449316907): + Default value, unused. + """ + + UNDEFINED_TARGET_SHAPE = 0 + ANY = 64972 + ANY_SINGLE_ZONE = 61100880 + BALANCED = 468409608 + TARGET_SHAPE_UNSPECIFIED = 449316907 + + target_shape: str = proto.Field( + proto.STRING, + number=338621299, + optional=True, + ) + zones: MutableSequence[ + "CapacityAdviceRequestDistributionPolicyZoneConfiguration" + ] = proto.RepeatedField( + proto.MESSAGE, + number=116085319, + message="CapacityAdviceRequestDistributionPolicyZoneConfiguration", + ) + + +class CapacityAdviceRequestDistributionPolicyZoneConfiguration(proto.Message): + r"""Zone configuration for the distribution policy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + zone (str): + The URL of the zone. It can be a + partial or full URL. For example, the following + are valid values: + + + - + https://www.googleapis.com/compute/v1/projects/project/zones/zone + - projects/project/zones/zone + - zones/zone + + This field is a member of `oneof`_ ``_zone``. + """ + + zone: str = proto.Field( + proto.STRING, + number=3744684, + optional=True, + ) + + +class CapacityAdviceRequestInstanceFlexibilityPolicy(proto.Message): + r"""Specification of alternative, flexible instance + configurations. + + Attributes: + instance_selections (MutableMapping[str, google.cloud.compute_v1.types.CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection]): + Named instance selections to configure + properties. The key is an arbitrary, unique + RFC1035 string that identifies the instance + selection. + """ + + instance_selections: MutableMapping[ + str, "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=22954577, + message="CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + ) + + +class CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection(proto.Message): + r"""Machine specification. + + Attributes: + disks (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk]): + Local SSDs. + guest_accelerators (MutableSequence[google.cloud.compute_v1.types.AcceleratorConfig]): + Accelerators configuration. + machine_types (MutableSequence[str]): + Full machine-type names, e.g. + "n1-standard-16". + """ + + disks: MutableSequence[ + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk" + ] = proto.RepeatedField( + proto.MESSAGE, + number=95594102, + message="CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + ) + guest_accelerators: MutableSequence["AcceleratorConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=463595119, + message="AcceleratorConfig", + ) + machine_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=79720065, + ) + + +class CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk( + proto.Message +): + r"""Attached disk configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (str): + Specifies the type of the disk. + Check the Type enum for the list of possible + values. + + This field is a member of `oneof`_ ``_type``. + """ + + class Type(proto.Enum): + r"""Specifies the type of the disk. + + Values: + UNDEFINED_TYPE (0): + A value indicating that the enum field is not + set. + DISK_TYPE_UNSPECIFIED (333621236): + Default value, unspecified disk type. + SCRATCH (496778970): + Scratch disk (Local SSD). + """ + + UNDEFINED_TYPE = 0 + DISK_TYPE_UNSPECIFIED = 333621236 + SCRATCH = 496778970 + + type_: str = proto.Field( + proto.STRING, + number=3575610, + optional=True, + ) + + +class CapacityAdviceRequestInstanceProperties(proto.Message): + r"""Instance provisioning properties. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scheduling (google.cloud.compute_v1.types.CapacityAdviceRequestInstancePropertiesScheduling): + Specifies the scheduling options. + + This field is a member of `oneof`_ ``_scheduling``. + """ + + scheduling: "CapacityAdviceRequestInstancePropertiesScheduling" = proto.Field( + proto.MESSAGE, + number=386688404, + optional=True, + message="CapacityAdviceRequestInstancePropertiesScheduling", + ) + + +class CapacityAdviceRequestInstancePropertiesScheduling(proto.Message): + r"""Defines the instance scheduling options. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + provisioning_model (str): + Specifies the provisioning model. + Check the ProvisioningModel enum for the list of + possible values. + + This field is a member of `oneof`_ ``_provisioning_model``. + """ + + class ProvisioningModel(proto.Enum): + r"""Specifies the provisioning model. + + Values: + UNDEFINED_PROVISIONING_MODEL (0): + A value indicating that the enum field is not + set. + FLEX_START (101746812): + Instance is provisioned using the Flex Start + provisioning model and has a limited runtime. + RESERVATION_BOUND (293538571): + Bound to the lifecycle of the reservation in + which it is provisioned. + SPOT (2552066): + Heavily discounted, no guaranteed runtime. + STANDARD (484642493): + Standard provisioning with user controlled + runtime, no discounts. + """ + + UNDEFINED_PROVISIONING_MODEL = 0 + FLEX_START = 101746812 + RESERVATION_BOUND = 293538571 + SPOT = 2552066 + STANDARD = 484642493 + + provisioning_model: str = proto.Field( + proto.STRING, + number=494423, + optional=True, + ) + + +class CapacityAdviceResponse(proto.Message): + r"""A response contains scoring recommendations. + + Attributes: + recommendations (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceResponseRecommendation]): + Initially the API will provide one + recommendation which balances the individual + scores according to the service provider's + preference. + """ + + recommendations: MutableSequence["CapacityAdviceResponseRecommendation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=324515802, + message="CapacityAdviceResponseRecommendation", + ) + ) + + +class CapacityAdviceResponseRecommendation(proto.Message): + r"""Recommendation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scores (google.cloud.compute_v1.types.CapacityAdviceResponseRecommendationScores): + Scores for the recommendation. + + This field is a member of `oneof`_ ``_scores``. + shards (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceResponseRecommendationShard]): + Shards represent blocks of uniform capacity + in recommendations. + """ + + scores: "CapacityAdviceResponseRecommendationScores" = proto.Field( + proto.MESSAGE, + number=165975073, + optional=True, + message="CapacityAdviceResponseRecommendationScores", + ) + shards: MutableSequence["CapacityAdviceResponseRecommendationShard"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=170175573, + message="CapacityAdviceResponseRecommendationShard", + ) + ) + + +class CapacityAdviceResponseRecommendationScores(proto.Message): + r"""Groups information about a shard of capacity. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + estimated_uptime (str): + The estimated run time of the majority of + Spot VMs in the request before preemption. The + estimate is best-effort only. It is based on + historical data and current conditions. + + This field is a member of `oneof`_ ``_estimated_uptime``. + obtainability (float): + The obtainability score indicates the + likelihood of successfully obtaining + (provisioning) the requested number of VMs. The + score range is 0.0 through 1.0. Higher is + better. + + This field is a member of `oneof`_ ``_obtainability``. + """ + + estimated_uptime: str = proto.Field( + proto.STRING, + number=223976779, + optional=True, + ) + obtainability: float = proto.Field( + proto.DOUBLE, + number=260735205, + optional=True, + ) + + +class CapacityAdviceResponseRecommendationShard(proto.Message): + r"""Shards represent blocks of uniform capacity in + recommendations. Each shard is for a single zone and a single + machine shape. Each shard defines a size expressed as the number + of VMs. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_count (int): + The number of instances. + + This field is a member of `oneof`_ ``_instance_count``. + machine_type (str): + The machine type corresponds to the instance + selection in the request. + + This field is a member of `oneof`_ ``_machine_type``. + provisioning_model (str): + The provisioning model that you want to view + recommendations for. Check the ProvisioningModel + enum for the list of possible values. + + This field is a member of `oneof`_ ``_provisioning_model``. + zone (str): + Output only. The zone name for this shard. + + This field is a member of `oneof`_ ``_zone``. + """ + + class ProvisioningModel(proto.Enum): + r"""The provisioning model that you want to view recommendations + for. + + Values: + UNDEFINED_PROVISIONING_MODEL (0): + A value indicating that the enum field is not + set. + FLEX_START (101746812): + Instance is provisioned using the Flex Start + provisioning model and has a limited runtime. + RESERVATION_BOUND (293538571): + Bound to the lifecycle of the reservation in + which it is provisioned. + SPOT (2552066): + Heavily discounted, no guaranteed runtime. + STANDARD (484642493): + Standard provisioning with user controlled + runtime, no discounts. + """ + + UNDEFINED_PROVISIONING_MODEL = 0 + FLEX_START = 101746812 + RESERVATION_BOUND = 293538571 + SPOT = 2552066 + STANDARD = 484642493 + + instance_count: int = proto.Field( + proto.INT32, + number=77317349, + optional=True, + ) + machine_type: str = proto.Field( + proto.STRING, + number=227711026, + optional=True, + ) + provisioning_model: str = proto.Field( + proto.STRING, + number=494423, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + optional=True, + ) + + +class CapacityAdviceRpcRequest(proto.Message): + r"""A request message for Advice.Capacity. See the method + description for details. + + Attributes: + capacity_advice_request_resource (google.cloud.compute_v1.types.CapacityAdviceRequest): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + """ + + capacity_advice_request_resource: "CapacityAdviceRequest" = proto.Field( + proto.MESSAGE, + number=176354208, + message="CapacityAdviceRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + +class CapacityHistoryAdviceRequest(proto.Message): + r"""A request message for Advice.CapacityHistory. See the method + description for details. + + Attributes: + capacity_history_request_resource (google.cloud.compute_v1.types.CapacityHistoryRequest): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + """ + + capacity_history_request_resource: "CapacityHistoryRequest" = proto.Field( + proto.MESSAGE, + number=182030318, + message="CapacityHistoryRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + +class CapacityHistoryRequest(proto.Message): + r"""A request to get the capacity history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_properties (google.cloud.compute_v1.types.CapacityHistoryRequestInstanceProperties): + Instance properties for this request. + + This field is a member of `oneof`_ ``_instance_properties``. + location_policy (google.cloud.compute_v1.types.CapacityHistoryRequestLocationPolicy): + Location policy for this request. + + This field is a member of `oneof`_ ``_location_policy``. + types (MutableSequence[str]): + List of history types to get capacity history + for. Check the Types enum for the list of + possible values. + """ + + class Types(proto.Enum): + r""" + + Values: + UNDEFINED_TYPES (0): + A value indicating that the enum field is not + set. + HISTORY_TYPE_UNSPECIFIED (58549757): + Default value, unused. + PREEMPTION (512869337): + Preemption history. + PRICE (76396841): + Price history. + """ + + UNDEFINED_TYPES = 0 + HISTORY_TYPE_UNSPECIFIED = 58549757 + PREEMPTION = 512869337 + PRICE = 76396841 + + instance_properties: "CapacityHistoryRequestInstanceProperties" = proto.Field( + proto.MESSAGE, + number=215355165, + optional=True, + message="CapacityHistoryRequestInstanceProperties", + ) + location_policy: "CapacityHistoryRequestLocationPolicy" = proto.Field( + proto.MESSAGE, + number=465689852, + optional=True, + message="CapacityHistoryRequestLocationPolicy", + ) + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=110844025, + ) + + +class CapacityHistoryRequestInstanceProperties(proto.Message): + r"""Instance properties for this request. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + machine_type (str): + The machine type for the VM, such as ``n2-standard-4``. + + This field is a member of `oneof`_ ``_machine_type``. + scheduling (google.cloud.compute_v1.types.CapacityHistoryRequestInstancePropertiesScheduling): + Specifies the scheduling options. + + This field is a member of `oneof`_ ``_scheduling``. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=227711026, + optional=True, + ) + scheduling: "CapacityHistoryRequestInstancePropertiesScheduling" = proto.Field( + proto.MESSAGE, + number=386688404, + optional=True, + message="CapacityHistoryRequestInstancePropertiesScheduling", + ) + + +class CapacityHistoryRequestInstancePropertiesScheduling(proto.Message): + r"""Scheduling options. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + provisioning_model (str): + The provisioning model to get capacity + history for. This field must be set to SPOT. + + For more information, see + Compute Engine instances provisioning models. + Check the ProvisioningModel enum for the list of + possible values. + + This field is a member of `oneof`_ ``_provisioning_model``. + """ + + class ProvisioningModel(proto.Enum): + r"""The provisioning model to get capacity history for. + This field must be set to SPOT. + + For more information, see + Compute Engine instances provisioning models. + + Values: + UNDEFINED_PROVISIONING_MODEL (0): + A value indicating that the enum field is not + set. + FLEX_START (101746812): + Instance is provisioned using the Flex Start + provisioning model and has a limited runtime. + RESERVATION_BOUND (293538571): + Bound to the lifecycle of the reservation in + which it is provisioned. + SPOT (2552066): + Heavily discounted, no guaranteed runtime. + STANDARD (484642493): + Standard provisioning with user controlled + runtime, no discounts. + """ + + UNDEFINED_PROVISIONING_MODEL = 0 + FLEX_START = 101746812 + RESERVATION_BOUND = 293538571 + SPOT = 2552066 + STANDARD = 484642493 + + provisioning_model: str = proto.Field( + proto.STRING, + number=494423, + optional=True, + ) + + +class CapacityHistoryRequestLocationPolicy(proto.Message): + r"""Location policy for this request. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (str): + The region or zone to get capacity history + for. + It can be a partial or full URL. For example, + the following are valid values: + + + - + https://www.googleapis.com/compute/v1/projects/project/zones/zone + - projects/project/zones/zone + - zones/zone + + This field is optional. + + This field is a member of `oneof`_ ``_location``. + """ + + location: str = proto.Field( + proto.STRING, + number=290430901, + optional=True, + ) + + +class CapacityHistoryResponse(proto.Message): + r"""Contains the capacity history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (str): + Output only. The location (region or zone) + for which the capacity history is returned. It + is returned as a URL - For + example,https://www.googleapis.com/compute/v1/projects/project/zones/zone. + + This field is a member of `oneof`_ ``_location``. + machine_type (str): + The machine type for which the capacity + history is returned. + + This field is a member of `oneof`_ ``_machine_type``. + preemption_history (MutableSequence[google.cloud.compute_v1.types.CapacityHistoryResponsePreemptionRecord]): + The preemption history for the requested + machine type and location. + price_history (MutableSequence[google.cloud.compute_v1.types.CapacityHistoryResponsePriceRecord]): + The price history for the requested machine + type and location. + """ + + location: str = proto.Field( + proto.STRING, + number=290430901, + optional=True, + ) + machine_type: str = proto.Field( + proto.STRING, + number=227711026, + optional=True, + ) + preemption_history: MutableSequence["CapacityHistoryResponsePreemptionRecord"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=364018222, + message="CapacityHistoryResponsePreemptionRecord", + ) + ) + price_history: MutableSequence["CapacityHistoryResponsePriceRecord"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=326230942, + message="CapacityHistoryResponsePriceRecord", + ) + ) + + +class CapacityHistoryResponsePreemptionRecord(proto.Message): + r"""A record of Spot VM preemption history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + interval (google.cloud.compute_v1.types.Interval): + The time interval for this preemption record. + + This field is a member of `oneof`_ ``_interval``. + preemption_rate (float): + The preemption rate during the interval, + representing the fraction of Spot VMs that were + preempted. Range: 0.0 to 1.0. Preemption rate is + calculated as (total preempted Spots) / (total + Spots that stopped running). + + This field is a member of `oneof`_ ``_preemption_rate``. + """ + + interval: "Interval" = proto.Field( + proto.MESSAGE, + number=33547461, + optional=True, + message="Interval", + ) + preemption_rate: float = proto.Field( + proto.DOUBLE, + number=140651910, + optional=True, + ) + + +class CapacityHistoryResponsePriceRecord(proto.Message): + r"""A record of price history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + interval (google.cloud.compute_v1.types.Interval): + The time interval for this price record. + + This field is a member of `oneof`_ ``_interval``. + list_price (google.cloud.compute_v1.types.Money): + The Spot VM list price during the interval. + + This field is a member of `oneof`_ ``_list_price``. + """ + + interval: "Interval" = proto.Field( + proto.MESSAGE, + number=33547461, + optional=True, + message="Interval", + ) + list_price: "Money" = proto.Field( + proto.MESSAGE, + number=167990888, + optional=True, + message="Money", + ) + + class CircuitBreakers(proto.Message): r"""Settings controlling the volume of requests, connections and retries to this backend service. @@ -26139,12 +26978,14 @@ class Commitment(proto.Message): GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, - STORAGE_OPTIMIZED_Z3. For example, type MEMORY_OPTIMIZED - specifies a commitment that applies only to eligible - resources of memory optimized M1 and M2 machine series. Type - GENERAL_PURPOSE specifies a commitment that applies only to - eligible resources of general purpose N1 machine series. - Check the Type enum for the list of possible values. + STORAGE_OPTIMIZED_Z3,STORAGE_OPTIMIZED_Z4DS, + STORAGE_OPTIMIZED_Z4DH,STORAGE_OPTIMIZED_Z4D4T. For example, + type MEMORY_OPTIMIZED specifies a commitment that applies + only to eligible resources of memory optimized M1 and M2 + machine series. Type GENERAL_PURPOSE specifies a commitment + that applies only to eligible resources of general purpose + N1 machine series. Check the Type enum for the list of + possible values. This field is a member of `oneof`_ ``_type``. """ @@ -26248,11 +27089,13 @@ class Type(proto.Enum): GENERAL_PURPOSE_N2D,GENERAL_PURPOSE_N4, GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, - MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, STORAGE_OPTIMIZED_Z3. For - example, type MEMORY_OPTIMIZED specifies a commitment that applies - only to eligible resources of memory optimized M1 and M2 machine - series. Type GENERAL_PURPOSE specifies a commitment that applies - only to eligible resources of general purpose N1 machine series. + MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, + STORAGE_OPTIMIZED_Z3,STORAGE_OPTIMIZED_Z4DS, + STORAGE_OPTIMIZED_Z4DH,STORAGE_OPTIMIZED_Z4D4T. For example, type + MEMORY_OPTIMIZED specifies a commitment that applies only to + eligible resources of memory optimized M1 and M2 machine series. + Type GENERAL_PURPOSE specifies a commitment that applies only to + eligible resources of general purpose N1 machine series. Values: UNDEFINED_TYPE (0): @@ -26350,6 +27193,12 @@ class Type(proto.Enum): CUD bucket for NETWORK_OPTIMIZED_U4S machines. STORAGE_OPTIMIZED_Z3 (316796085): No description available. + STORAGE_OPTIMIZED_Z4D4T (18503022): + CUD bucket for Z4D-4T machines. + STORAGE_OPTIMIZED_Z4DH (35233722): + CUD bucket for Z4DH machines. + STORAGE_OPTIMIZED_Z4DS (35233733): + CUD bucket for Z4DS machines. TYPE_UNSPECIFIED (437714322): Note for internal users: When adding a new enum Type for v1, make sure to also add it in the comment for the @@ -26401,6 +27250,9 @@ class Type(proto.Enum): NETWORK_OPTIMIZED_U4P = 147044872 NETWORK_OPTIMIZED_U4S = 147044875 STORAGE_OPTIMIZED_Z3 = 316796085 + STORAGE_OPTIMIZED_Z4D4T = 18503022 + STORAGE_OPTIMIZED_Z4DH = 35233722 + STORAGE_OPTIMIZED_Z4DS = 35233733 TYPE_UNSPECIFIED = 437714322 auto_renew: bool = proto.Field( @@ -46903,6 +47755,29 @@ class GetProjectRequest(proto.Message): ) +class GetProjectViewRequest(proto.Message): + r"""A request message for ProjectViews.Get. See the method + description for details. + + Attributes: + project (str): + Required. Project ID for this request. This + is part of the URL path. + region (str): + Required. Name of the region for this + request. This is part of the URL path. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetPublicAdvertisedPrefixeRequest(proto.Message): r"""A request message for PublicAdvertisedPrefixes.Get. See the method description for details. @@ -50810,6 +51685,9 @@ class Type(proto.Enum): set. BARE_METAL_LINUX_COMPATIBLE (354232740): No description available. + BMSAI_CAPABLE (449302109): + Indicates the guest OS is capable of Bare + Metal Secure AI (BMSAI) confidential computing. CCA_CAPABLE (79012270): No description available. FEATURE_TYPE_UNSPECIFIED (531767259): @@ -50847,6 +51725,7 @@ class Type(proto.Enum): UNDEFINED_TYPE = 0 BARE_METAL_LINUX_COMPATIBLE = 354232740 + BMSAI_CAPABLE = 449302109 CCA_CAPABLE = 79012270 FEATURE_TYPE_UNSPECIFIED = 531767259 GVNIC = 68209305 @@ -66772,7 +67651,15 @@ class InstancePropertiesPatch(proto.Message): r"""Represents the change that you want to make to the instance properties. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: + expose_host_topology (bool): + This optional flag exposes the hashed + physical host ID. + + This field is a member of `oneof`_ ``_expose_host_topology``. labels (MutableMapping[str, str]): The label key-value pairs that you want to patch onto the instance. @@ -66782,6 +67669,11 @@ class InstancePropertiesPatch(proto.Message): see Project and instance metadata. """ + expose_host_topology: bool = proto.Field( + proto.BOOL, + number=428530155, + optional=True, + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -75374,6 +76266,47 @@ class InterconnectsGetMacsecConfigResponse(proto.Message): ) +class Interval(proto.Message): + r"""Represents a time interval, encoded as a Timestamp start + (inclusive) and a Timestamp end (exclusive). + + The start must be less than or equal to the end. + When the start equals the end, the interval is empty (matches no + time). When both start and end are unspecified, the interval + matches any time. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + end_time (str): + Optional. Exclusive end of the interval. + + If specified, a Timestamp matching this interval + will have to be before the end. + + This field is a member of `oneof`_ ``_end_time``. + start_time (str): + Optional. Inclusive start of the interval. + + If specified, a Timestamp matching this interval + will have to be the same or after the start. + + This field is a member of `oneof`_ ``_start_time``. + """ + + end_time: str = proto.Field( + proto.STRING, + number=114938801, + optional=True, + ) + start_time: str = proto.Field( + proto.STRING, + number=37467274, + optional=True, + ) + + class InvalidateCacheUrlMapRequest(proto.Message): r"""A request message for UrlMaps.InvalidateCache. See the method description for details. @@ -101728,6 +102661,51 @@ class MetadataFilterLabelMatch(proto.Message): ) +class Money(proto.Message): + r"""Represents an amount of money with its currency type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + currency_code (str): + The three-letter currency code defined in ISO + 4217. + + This field is a member of `oneof`_ ``_currency_code``. + nanos (int): + Number of nano (10^-9) units of the amount. The value must + be between -999,999,999 and +999,999,999 inclusive. If + ``units`` is positive, ``nanos`` must be positive or zero. + If ``units`` is zero, ``nanos`` can be positive, zero, or + negative. If ``units`` is negative, ``nanos`` must be + negative or zero. For example $-1.75 is represented as + ``units``\ =-1 and ``nanos``\ =-750,000,000. + + This field is a member of `oneof`_ ``_nanos``. + units (int): + The whole units of the amount. For example if + ``currencyCode`` is ``"USD"``, then 1 unit is one US dollar. + + This field is a member of `oneof`_ ``_units``. + """ + + currency_code: str = proto.Field( + proto.STRING, + number=34986331, + optional=True, + ) + nanos: int = proto.Field( + proto.INT32, + number=104586303, + optional=True, + ) + units: int = proto.Field( + proto.INT64, + number=111433583, + optional=True, + ) + + class MoveAddressRequest(proto.Message): r"""A request message for Addresses.Move. See the method description for details. @@ -117263,6 +118241,35 @@ class XpnProjectStatus(proto.Enum): ) +class ProjectView(proto.Message): + r"""Represents a ProjectView resource. + + A ProjectView resource contains read-only project data which is + available globally. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (google.cloud.compute_v1.types.Project): + The project data. The returned Project data does not contain + regional or zonal quota usage data. Global quota limits are + present. For accurate, real-time quota usage numbers, query + the global + `projects.get `__ + endpoint. + + This field is a member of `oneof`_ ``_project``. + """ + + project: "Project" = proto.Field( + proto.MESSAGE, + number=227560217, + optional=True, + message="Project", + ) + + class ProjectsDisableXpnResourceRequest(proto.Message): r""" @@ -133592,6 +134599,12 @@ class Scheduling(proto.Message): attached to the instance. This field is a member of `oneof`_ ``_availability_domain``. + expose_host_topology (bool): + This optional flag exposes the hashed + physical host ID in the ResourceStatus resource + of the VM. + + This field is a member of `oneof`_ ``_expose_host_topology``. graceful_shutdown (google.cloud.compute_v1.types.SchedulingGracefulShutdown): This field is a member of `oneof`_ ``_graceful_shutdown``. @@ -133781,6 +134794,11 @@ class ProvisioningModel(proto.Enum): number=252514344, optional=True, ) + expose_host_topology: bool = proto.Field( + proto.BOOL, + number=428530155, + optional=True, + ) graceful_shutdown: "SchedulingGracefulShutdown" = proto.Field( proto.MESSAGE, number=226325136, diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_history_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_history_sync.py new file mode 100644 index 000000000000..54d425faba73 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_history_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CapacityHistory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Advice_CapacityHistory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_capacity_history(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityHistoryAdviceRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity_history(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Advice_CapacityHistory_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_sync.py new file mode 100644 index 000000000000..0c07e76daf08 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Capacity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Advice_Capacity_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_capacity(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityAdviceRpcRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Advice_Capacity_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_project_views_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_project_views_get_sync.py new file mode 100644 index 000000000000..f19a30336f0f --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_project_views_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_ProjectViews_Get_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get(): + # Create a client + client = compute_v1.ProjectViewsClient() + + # Initialize request argument(s) + request = compute_v1.GetProjectViewRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_ProjectViews_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json index 6490cbcf0a8b..2936d512f86c 100644 --- a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json +++ b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-compute", - "version": "1.53.0" + "version": "1.54.0" }, "snippets": [ { @@ -1055,6 +1055,182 @@ ], "title": "compute_v1_generated_advice_calendar_mode_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.AdviceClient", + "shortName": "AdviceClient" + }, + "fullName": "google.cloud.compute_v1.AdviceClient.capacity_history", + "method": { + "fullName": "google.cloud.compute.v1.Advice.CapacityHistory", + "service": { + "fullName": "google.cloud.compute.v1.Advice", + "shortName": "Advice" + }, + "shortName": "CapacityHistory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.CapacityHistoryAdviceRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "capacity_history_request_resource", + "type": "google.cloud.compute_v1.types.CapacityHistoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.CapacityHistoryResponse", + "shortName": "capacity_history" + }, + "description": "Sample for CapacityHistory", + "file": "compute_v1_generated_advice_capacity_history_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Advice_CapacityHistory_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_advice_capacity_history_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.AdviceClient", + "shortName": "AdviceClient" + }, + "fullName": "google.cloud.compute_v1.AdviceClient.capacity", + "method": { + "fullName": "google.cloud.compute.v1.Advice.Capacity", + "service": { + "fullName": "google.cloud.compute.v1.Advice", + "shortName": "Advice" + }, + "shortName": "Capacity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.CapacityAdviceRpcRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "capacity_advice_request_resource", + "type": "google.cloud.compute_v1.types.CapacityAdviceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.CapacityAdviceResponse", + "shortName": "capacity" + }, + "description": "Sample for Capacity", + "file": "compute_v1_generated_advice_capacity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Advice_Capacity_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_advice_capacity_sync.py" + }, { "canonical": true, "clientMethod": { @@ -41171,6 +41347,90 @@ ], "title": "compute_v1_generated_preview_features_update_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ProjectViewsClient", + "shortName": "ProjectViewsClient" + }, + "fullName": "google.cloud.compute_v1.ProjectViewsClient.get", + "method": { + "fullName": "google.cloud.compute.v1.ProjectViews.Get", + "service": { + "fullName": "google.cloud.compute.v1.ProjectViews", + "shortName": "ProjectViews" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetProjectViewRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.ProjectView", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_project_views_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_ProjectViews_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_project_views_get_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py index b7e09710dea1..03a997a86080 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py @@ -1073,90 +1073,874 @@ def test_calendar_mode_rest_flattened_error(transport: str = "rest"): ) +def test_capacity_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.capacity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.capacity] = mock_rpc + + request = {} + client.capacity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.capacity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_capacity_rest_required_fields(request_type=compute.CapacityAdviceRpcRequest): + transport_class = transports.AdviceRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCapacity, + "_BaseCapacity__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.CapacityAdviceResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CapacityAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.capacity(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_capacity_rest_flattened(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CapacityAdviceResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + capacity_advice_request_resource=compute.CapacityAdviceRequest( + distribution_policy=compute.CapacityAdviceRequestDistributionPolicy( + target_shape="target_shape_value" + ) + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.CapacityAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.capacity(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/advice/capacity" + % client.transport._host, + args[1], + ) + + +def test_capacity_rest_flattened_error(transport: str = "rest"): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.capacity( + compute.CapacityAdviceRpcRequest(), + project="project_value", + region="region_value", + capacity_advice_request_resource=compute.CapacityAdviceRequest( + distribution_policy=compute.CapacityAdviceRequestDistributionPolicy( + target_shape="target_shape_value" + ) + ), + ) + + +def test_capacity_history_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.capacity_history in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.capacity_history] = ( + mock_rpc + ) + + request = {} + client.capacity_history(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.capacity_history(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_capacity_history_rest_required_fields( + request_type=compute.CapacityHistoryAdviceRequest, +): + transport_class = transports.AdviceRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCapacityHistory, + "_BaseCapacityHistory__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.CapacityHistoryResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CapacityHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.capacity_history(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_capacity_history_rest_flattened(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CapacityHistoryResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + capacity_history_request_resource=compute.CapacityHistoryRequest( + instance_properties=compute.CapacityHistoryRequestInstanceProperties( + machine_type="machine_type_value" + ) + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.CapacityHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.capacity_history(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/advice/capacityHistory" + % client.transport._host, + args[1], + ) + + +def test_capacity_history_rest_flattened_error(transport: str = "rest"): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.capacity_history( + compute.CapacityHistoryAdviceRequest(), + project="project_value", + region="region_value", + capacity_history_request_resource=compute.CapacityHistoryRequest( + instance_properties=compute.CapacityHistoryRequestInstanceProperties( + machine_type="machine_type_value" + ) + ), + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AdviceRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) - with pytest.raises(ValueError): - client = AdviceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + with pytest.raises(ValueError): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdviceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdviceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdviceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdviceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AdviceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AdviceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = AdviceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_calendar_mode_rest_bad_request( + request_type=compute.CalendarModeAdviceRpcRequest, +): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.calendar_mode(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CalendarModeAdviceRpcRequest, + dict, + ], +) +def test_calendar_mode_rest_call_success(request_type): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["calendar_mode_advice_request_resource"] = { + "future_resources_specs": {} + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.CalendarModeAdviceRpcRequest.meta.fields[ + "calendar_mode_advice_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "calendar_mode_advice_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["calendar_mode_advice_request_resource"][field]) + ): + del request_init["calendar_mode_advice_request_resource"][field][i][ + subfield + ] + else: + del request_init["calendar_mode_advice_request_resource"][field][ + subfield + ] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CalendarModeAdviceResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CalendarModeAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.calendar_mode(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.CalendarModeAdviceResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_calendar_mode_rest_interceptors(null_interceptor): + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AdviceRestInterceptor(), + ) + client = AdviceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AdviceRestInterceptor, "post_calendar_mode" + ) as post, + mock.patch.object( + transports.AdviceRestInterceptor, "post_calendar_mode_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.AdviceRestInterceptor, "pre_calendar_mode") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CalendarModeAdviceRpcRequest.pb( + compute.CalendarModeAdviceRpcRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.CalendarModeAdviceResponse.to_json( + compute.CalendarModeAdviceResponse() + ) + req.return_value.content = return_value + + request = compute.CalendarModeAdviceRpcRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.CalendarModeAdviceResponse() + post_with_metadata.return_value = compute.CalendarModeAdviceResponse(), metadata + + client.calendar_mode( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_capacity_rest_bad_request(request_type=compute.CapacityAdviceRpcRequest): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.capacity(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CapacityAdviceRpcRequest, + dict, + ], +) +def test_capacity_rest_call_success(request_type): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.AdviceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AdviceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["capacity_advice_request_resource"] = { + "distribution_policy": { + "target_shape": "target_shape_value", + "zones": [{"zone": "zone_value"}], + }, + "instance_flexibility_policy": {"instance_selections": {}}, + "instance_properties": { + "scheduling": {"provisioning_model": "provisioning_model_value"} + }, + "size": 443, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # It is an error to provide an api_key and a transport instance. - transport = transports.AdviceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdviceClient( - client_options=options, - transport=transport, - ) + # Determine if the message type is proto-plus or protobuf + test_field = compute.CapacityAdviceRpcRequest.meta.fields[ + "capacity_advice_request_resource" + ] - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdviceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] - # It is an error to provide scopes and a transport instance. - transport = transports.AdviceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AdviceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + subfields_not_in_runtime = [] -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "capacity_advice_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["capacity_advice_request_resource"][field]) + ): + del request_init["capacity_advice_request_resource"][field][i][ + subfield + ] + else: + del request_init["capacity_advice_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CapacityAdviceResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CapacityAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.capacity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.CapacityAdviceResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_capacity_rest_interceptors(null_interceptor): transport = transports.AdviceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AdviceRestInterceptor(), ) client = AdviceClient(transport=transport) - assert client.transport is transport + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.AdviceRestInterceptor, "post_capacity") as post, + mock.patch.object( + transports.AdviceRestInterceptor, "post_capacity_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.AdviceRestInterceptor, "pre_capacity") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CapacityAdviceRpcRequest.pb( + compute.CapacityAdviceRpcRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -@pytest.mark.parametrize( - "transport_class", - [ - transports.AdviceRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.CapacityAdviceResponse.to_json( + compute.CapacityAdviceResponse() + ) + req.return_value.content = return_value + request = compute.CapacityAdviceRpcRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.CapacityAdviceResponse() + post_with_metadata.return_value = compute.CapacityAdviceResponse(), metadata -def test_transport_kind_rest(): - transport = AdviceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.capacity( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_calendar_mode_rest_bad_request( - request_type=compute.CalendarModeAdviceRpcRequest, +def test_capacity_history_rest_bad_request( + request_type=compute.CapacityHistoryAdviceRequest, ): client = AdviceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -1178,33 +1962,38 @@ def test_calendar_mode_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.calendar_mode(request) + client.capacity_history(request) @pytest.mark.parametrize( "request_type", [ - compute.CalendarModeAdviceRpcRequest, + compute.CapacityHistoryAdviceRequest, dict, ], ) -def test_calendar_mode_rest_call_success(request_type): +def test_capacity_history_rest_call_success(request_type): client = AdviceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2"} - request_init["calendar_mode_advice_request_resource"] = { - "future_resources_specs": {} + request_init["capacity_history_request_resource"] = { + "instance_properties": { + "machine_type": "machine_type_value", + "scheduling": {"provisioning_model": "provisioning_model_value"}, + }, + "location_policy": {"location": "location_value"}, + "types": ["types_value1", "types_value2"], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = compute.CalendarModeAdviceRpcRequest.meta.fields[ - "calendar_mode_advice_request_resource" + test_field = compute.CapacityHistoryAdviceRequest.meta.fields[ + "capacity_history_request_resource" ] def get_message_fields(field): @@ -1234,7 +2023,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime for field, value in request_init[ - "calendar_mode_advice_request_resource" + "capacity_history_request_resource" ].items(): # pragma: NO COVER result = None is_repeated = False @@ -1266,40 +2055,43 @@ def get_message_fields(field): if subfield: if field_repeated: for i in range( - 0, len(request_init["calendar_mode_advice_request_resource"][field]) + 0, len(request_init["capacity_history_request_resource"][field]) ): - del request_init["calendar_mode_advice_request_resource"][field][i][ + del request_init["capacity_history_request_resource"][field][i][ subfield ] else: - del request_init["calendar_mode_advice_request_resource"][field][ - subfield - ] + del request_init["capacity_history_request_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.CalendarModeAdviceResponse() + return_value = compute.CapacityHistoryResponse( + location="location_value", + machine_type="machine_type_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.CalendarModeAdviceResponse.pb(return_value) + return_value = compute.CapacityHistoryResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.calendar_mode(request) + response = client.capacity_history(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.CalendarModeAdviceResponse) + assert isinstance(response, compute.CapacityHistoryResponse) + assert response.location == "location_value" + assert response.machine_type == "machine_type_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_calendar_mode_rest_interceptors(null_interceptor): +def test_capacity_history_rest_interceptors(null_interceptor): transport = transports.AdviceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.AdviceRestInterceptor(), @@ -1310,18 +2102,20 @@ def test_calendar_mode_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.AdviceRestInterceptor, "post_calendar_mode" + transports.AdviceRestInterceptor, "post_capacity_history" ) as post, mock.patch.object( - transports.AdviceRestInterceptor, "post_calendar_mode_with_metadata" + transports.AdviceRestInterceptor, "post_capacity_history_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.AdviceRestInterceptor, "pre_calendar_mode") as pre, + mock.patch.object( + transports.AdviceRestInterceptor, "pre_capacity_history" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.CalendarModeAdviceRpcRequest.pb( - compute.CalendarModeAdviceRpcRequest() + pb_message = compute.CapacityHistoryAdviceRequest.pb( + compute.CapacityHistoryAdviceRequest() ) transcode.return_value = { "method": "post", @@ -1333,21 +2127,21 @@ def test_calendar_mode_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = compute.CalendarModeAdviceResponse.to_json( - compute.CalendarModeAdviceResponse() + return_value = compute.CapacityHistoryResponse.to_json( + compute.CapacityHistoryResponse() ) req.return_value.content = return_value - request = compute.CalendarModeAdviceRpcRequest() + request = compute.CapacityHistoryAdviceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.CalendarModeAdviceResponse() - post_with_metadata.return_value = compute.CalendarModeAdviceResponse(), metadata + post.return_value = compute.CapacityHistoryResponse() + post_with_metadata.return_value = compute.CapacityHistoryResponse(), metadata - client.calendar_mode( + client.capacity_history( request, metadata=[ ("key", "val"), @@ -1386,6 +2180,44 @@ def test_calendar_mode_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_capacity_empty_call_rest(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.capacity), "__call__") as call: + client.capacity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CapacityAdviceRpcRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_capacity_history_empty_call_rest(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.capacity_history), "__call__") as call: + client.capacity_history(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CapacityHistoryAdviceRequest() + assert args[0] == request_msg + + def test_advice_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -1407,7 +2239,11 @@ def test_advice_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. - methods = ("calendar_mode",) + methods = ( + "calendar_mode", + "capacity", + "capacity_history", + ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) @@ -1553,6 +2389,12 @@ def test_advice_client_transport_session_collision(transport_name): session1 = client1.transport.calendar_mode._session session2 = client2.transport.calendar_mode._session assert session1 != session2 + session1 = client1.transport.capacity._session + session2 = client2.transport.capacity._session + assert session1 != session2 + session1 = client1.transport.capacity_history._session + session2 = client2.transport.capacity_history._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py index d2ebd413ba2d..69027751fb47 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py @@ -3932,7 +3932,7 @@ def test_insert_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3978,7 +3978,7 @@ def test_insert_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4129,7 +4129,7 @@ def test_insert_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4175,7 +4175,7 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5405,7 +5405,7 @@ def test_patch_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5452,7 +5452,7 @@ def test_patch_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5612,7 +5612,7 @@ def test_patch_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5659,7 +5659,7 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11734,7 +11734,9 @@ def test_insert_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"project": "sample1", "zone": "sample2"} request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -12718,7 +12720,9 @@ def test_patch_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py index 91c1ec04b9f6..4215877a0b11 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py @@ -3738,6 +3738,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py index 67a5928a5245..996cf6e6bd2a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py @@ -20597,6 +20597,7 @@ def test_bulk_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, @@ -22752,6 +22753,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": {"enabled": True, "max_duration": {}}, "host_error_timeout_seconds": 2811, "instance_termination_action": "instance_termination_action_value", @@ -26523,6 +26525,7 @@ def test_set_scheduling_rest_call_success(request_type): request_init["scheduling_resource"] = { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, @@ -29137,6 +29140,7 @@ def test_update_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": {"enabled": True, "max_duration": {}}, "host_error_timeout_seconds": 2811, "instance_termination_action": "instance_termination_action_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py index 7f5e262376a3..989682fa38d2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py @@ -3695,6 +3695,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_project_views.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_project_views.py new file mode 100644 index 000000000000..3c63195a7d87 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_project_views.py @@ -0,0 +1,1650 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1.services.project_views import ( + ProjectViewsClient, + transports, +) +from google.cloud.compute_v1.types import compute + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ProjectViewsClient._get_client_cert_source(None, False) is None + assert ( + ProjectViewsClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ProjectViewsClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ProjectViewsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ProjectViewsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ProjectViewsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ProjectViewsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ProjectViewsClient, "rest"), + ], +) +def test_project_views_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ProjectViewsRestTransport, "rest"), + ], +) +def test_project_views_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ProjectViewsClient, "rest"), + ], +) +def test_project_views_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_project_views_client_get_transport_class(): + transport = ProjectViewsClient.get_transport_class() + available_transports = [ + transports.ProjectViewsRestTransport, + ] + assert transport in available_transports + + transport = ProjectViewsClient.get_transport_class("rest") + assert transport == transports.ProjectViewsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest"), + ], +) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +def test_project_views_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ProjectViewsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ProjectViewsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", "true"), + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_project_views_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ProjectViewsClient]) +@mock.patch.object( + ProjectViewsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectViewsClient) +) +def test_project_views_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [ProjectViewsClient]) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +def test_project_views_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ProjectViewsClient._DEFAULT_UNIVERSE + default_endpoint = ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest"), + ], +) +def test_project_views_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", None), + ], +) +def test_project_views_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_get_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get] = mock_rpc + + request = {} + client.get(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_rest_required_fields(request_type=compute.GetProjectViewRequest): + transport_class = transports.ProjectViewsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGet, + "_BaseGet__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ProjectView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_flattened(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.ProjectView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/projectViews" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetProjectViewRequest(), + project="project_value", + region="region_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProjectViewsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectViewsRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = ProjectViewsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetProjectViewRequest): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetProjectViewRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ProjectView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.ProjectView) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectViewsRestInterceptor(), + ) + client = ProjectViewsClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.ProjectViewsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.ProjectViewsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.ProjectViewsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetProjectViewRequest.pb(compute.GetProjectViewRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.ProjectView.to_json(compute.ProjectView()) + req.return_value.content = return_value + + request = compute.GetProjectViewRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ProjectView() + post_with_metadata.return_value = compute.ProjectView(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_empty_call_rest(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get), "__call__") as call: + client.get(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetProjectViewRequest() + assert args[0] == request_msg + + +def test_project_views_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProjectViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_project_views_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.project_views.transports.ProjectViewsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ProjectViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("get",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_project_views_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.compute_v1.services.project_views.transports.ProjectViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectViewsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_project_views_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.compute_v1.services.project_views.transports.ProjectViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectViewsTransport() + adc.assert_called_once() + + +def test_project_views_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ProjectViewsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_project_views_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ProjectViewsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_project_views_host_no_port(transport_name): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_project_views_host_with_port(transport_name): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_project_views_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProjectViewsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProjectViewsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ProjectViewsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ProjectViewsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ProjectViewsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ProjectViewsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ProjectViewsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ProjectViewsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ProjectViewsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ProjectViewsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = ProjectViewsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ProjectViewsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ProjectViewsTransport, "_prep_wrapped_messages" + ) as prep: + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ProjectViewsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ProjectViewsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py index d1a80769a011..7cd0e3e62fac 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py @@ -3684,7 +3684,7 @@ def test_insert_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3730,7 +3730,7 @@ def test_insert_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3881,7 +3881,7 @@ def test_insert_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3927,7 +3927,7 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5164,7 +5164,7 @@ def test_patch_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5211,7 +5211,7 @@ def test_patch_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5371,7 +5371,7 @@ def test_patch_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5418,7 +5418,7 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11365,7 +11365,9 @@ def test_insert_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2"} request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -12362,7 +12364,9 @@ def test_patch_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py index 79b394018b0c..c31b1e168c9c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py @@ -2740,6 +2740,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py index 86466717bc71..bd630e1b401c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py @@ -1567,6 +1567,7 @@ def test_bulk_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/packages/google-cloud-devicestreaming/CHANGELOG.md b/packages/google-cloud-devicestreaming/CHANGELOG.md index 0b7007b96d0a..8d46b2a0f42c 100644 --- a/packages/google-cloud-devicestreaming/CHANGELOG.md +++ b/packages/google-cloud-devicestreaming/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-devicestreaming/#history +## [0.5.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-devicestreaming-v0.5.0...google-cloud-devicestreaming-v0.5.1) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.5.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-devicestreaming-v0.4.0...google-cloud-devicestreaming-v0.5.0) (2026-06-02) diff --git a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/__init__.py b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/__init__.py index 8618090add6a..deecb361c738 100644 --- a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/__init__.py +++ b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/__init__.py @@ -38,6 +38,7 @@ from google.cloud.devicestreaming_v1.types.service import ( AndroidDevice, CancelDeviceSessionRequest, + ClientInfo, CreateDeviceSessionRequest, DeviceSession, GetDeviceSessionRequest, @@ -60,6 +61,7 @@ "StreamStatus", "AndroidDevice", "CancelDeviceSessionRequest", + "ClientInfo", "CreateDeviceSessionRequest", "DeviceSession", "GetDeviceSessionRequest", diff --git a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/gapic_version.py b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/gapic_version.py index 7d9863d19611..acc458e7fa6f 100644 --- a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/gapic_version.py +++ b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.0" # {x-release-please-version} +__version__ = "0.5.1" # {x-release-please-version} diff --git a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/__init__.py b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/__init__.py index b17311564677..43196d8890e5 100644 --- a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/__init__.py +++ b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/__init__.py @@ -50,6 +50,7 @@ from .types.service import ( AndroidDevice, CancelDeviceSessionRequest, + ClientInfo, CreateDeviceSessionRequest, DeviceSession, GetDeviceSessionRequest, @@ -63,6 +64,7 @@ "AdbMessage", "AndroidDevice", "CancelDeviceSessionRequest", + "ClientInfo", "Close", "CreateDeviceSessionRequest", "DeviceMessage", diff --git a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/gapic_version.py b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/gapic_version.py index 7d9863d19611..acc458e7fa6f 100644 --- a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/gapic_version.py +++ b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.0" # {x-release-please-version} +__version__ = "0.5.1" # {x-release-please-version} diff --git a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/__init__.py b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/__init__.py index 6af575b96de6..690bf637cd75 100644 --- a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/__init__.py +++ b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/__init__.py @@ -27,6 +27,7 @@ from .service import ( AndroidDevice, CancelDeviceSessionRequest, + ClientInfo, CreateDeviceSessionRequest, DeviceSession, GetDeviceSessionRequest, @@ -47,6 +48,7 @@ "StreamStatus", "AndroidDevice", "CancelDeviceSessionRequest", + "ClientInfo", "CreateDeviceSessionRequest", "DeviceSession", "GetDeviceSessionRequest", diff --git a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/service.py b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/service.py index cd256b563e12..9783b29a535a 100644 --- a/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/service.py +++ b/packages/google-cloud-devicestreaming/google/cloud/devicestreaming_v1/types/service.py @@ -32,6 +32,7 @@ "CancelDeviceSessionRequest", "UpdateDeviceSessionRequest", "DeviceSession", + "ClientInfo", "AndroidDevice", }, ) @@ -236,7 +237,10 @@ class DeviceSession(proto.Message): Output only. The timestamp that the session first became ACTIVE. android_device (google.cloud.devicestreaming_v1.types.AndroidDevice): - Required. The requested device + Required. The requested device. + client_info (google.cloud.devicestreaming_v1.types.ClientInfo): + Optional. Information about the client which + invoked the device session. """ class SessionState(proto.Enum): @@ -365,6 +369,34 @@ class SessionStateEvent(proto.Message): number=15, message="AndroidDevice", ) + client_info: "ClientInfo" = proto.Field( + proto.MESSAGE, + number=21, + message="ClientInfo", + ) + + +class ClientInfo(proto.Message): + r"""Information about the client which invoked the device + session. + + Attributes: + client (str): + Required. Client name, such as gcloud. The + maximum length is 64 characters. + version (str): + Optional. Client version. The maximum length + is 64 characters. + """ + + client: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) class AndroidDevice(proto.Message): diff --git a/packages/google-cloud-devicestreaming/samples/generated_samples/snippet_metadata_google.cloud.devicestreaming.v1.json b/packages/google-cloud-devicestreaming/samples/generated_samples/snippet_metadata_google.cloud.devicestreaming.v1.json index 4902c6106adf..adbfba0a1be9 100644 --- a/packages/google-cloud-devicestreaming/samples/generated_samples/snippet_metadata_google.cloud.devicestreaming.v1.json +++ b/packages/google-cloud-devicestreaming/samples/generated_samples/snippet_metadata_google.cloud.devicestreaming.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-devicestreaming", - "version": "0.5.0" + "version": "0.5.1" }, "snippets": [ { diff --git a/packages/google-cloud-devicestreaming/tests/unit/gapic/devicestreaming_v1/test_direct_access_service.py b/packages/google-cloud-devicestreaming/tests/unit/gapic/devicestreaming_v1/test_direct_access_service.py index 032164e01f73..2d1ebda3abb2 100644 --- a/packages/google-cloud-devicestreaming/tests/unit/gapic/devicestreaming_v1/test_direct_access_service.py +++ b/packages/google-cloud-devicestreaming/tests/unit/gapic/devicestreaming_v1/test_direct_access_service.py @@ -4494,6 +4494,7 @@ def test_create_device_session_rest_call_success(request_type): "locale": "locale_value", "orientation": "orientation_value", }, + "client_info": {"client": "client_value", "version": "version_value"}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -5101,6 +5102,7 @@ def test_update_device_session_rest_call_success(request_type): "locale": "locale_value", "orientation": "orientation_value", }, + "client_info": {"client": "client_value", "version": "version_value"}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency diff --git a/packages/google-cloud-discoveryengine/CHANGELOG.md b/packages/google-cloud-discoveryengine/CHANGELOG.md index 767aa7dc4256..f88b5a3e1613 100644 --- a/packages/google-cloud-discoveryengine/CHANGELOG.md +++ b/packages/google-cloud-discoveryengine/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-discoveryengine/#history +## [0.20.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-discoveryengine-v0.20.3...google-cloud-discoveryengine-v0.20.4) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.20.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-discoveryengine-v0.20.2...google-cloud-discoveryengine-v0.20.3) (2026-09-03) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py index 4e1e0acd42f2..352347146605 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.20.3" # {x-release-please-version} +__version__ = "0.20.4" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py index 4e1e0acd42f2..352347146605 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.20.3" # {x-release-please-version} +__version__ = "0.20.4" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/async_client.py index 1f63e70c7ede..4cd760160035 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/async_client.py @@ -80,6 +80,8 @@ class SearchServiceAsyncClient: parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) chunk_path = staticmethod(SearchServiceClient.chunk_path) parse_chunk_path = staticmethod(SearchServiceClient.parse_chunk_path) + control_path = staticmethod(SearchServiceClient.control_path) + parse_control_path = staticmethod(SearchServiceClient.parse_control_path) data_store_path = staticmethod(SearchServiceClient.data_store_path) parse_data_store_path = staticmethod(SearchServiceClient.parse_data_store_path) document_path = staticmethod(SearchServiceClient.document_path) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/client.py index 09a7a415e1fb..0042c003b218 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/client.py @@ -224,6 +224,30 @@ def parse_chunk_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def control_path( + project: str, + location: str, + data_store: str, + control: str, + ) -> str: + """Returns a fully-qualified control string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/controls/{control}".format( + project=project, + location=location, + data_store=data_store, + control=control, + ) + + @staticmethod + def parse_control_path(path: str) -> Dict[str, str]: + """Parses a control path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/controls/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def data_store_path( project: str, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/base.py index 57c453d0ef9f..1aa2c6933328 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/base.py @@ -39,7 +39,12 @@ class SearchServiceTransport(abc.ABC): """Abstract transport class for SearchService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/discoveryengine.assist.readwrite", + "https://www.googleapis.com/auth/discoveryengine.readwrite", + "https://www.googleapis.com/auth/discoveryengine.serving.readwrite", + ) DEFAULT_HOST: str = "discoveryengine.googleapis.com" diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py index 2c7c5187db75..083f2b9cb232 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py @@ -129,6 +129,11 @@ class SearchRequest(proto.Message): the specs directly under [SearchRequest][google.cloud.discoveryengine.v1.SearchRequest] should be used. + num_results_per_data_store (int): + Optional. The maximum number of results to retrieve from + each data store. If not specified, it will use the + [SearchRequest.DataStoreSpec.num_results][google.cloud.discoveryengine.v1.SearchRequest.DataStoreSpec.num_results] + if provided, otherwise there is no limit. filter (str): The filter syntax consists of an expression language for constructing a predicate from one or more fields of the @@ -348,6 +353,20 @@ class SearchRequest(proto.Message): proprietary Google model to determine the keyword-based overlap between the query and the document. - ``base_rank``: the default rank of the result + - ``media_actor_match``: whether the media actor matches the + query + - ``media_director_match``: whether the media director + matches the query + - ``media_genre_match``: whether the media genre matches the + query + - ``media_language_match``: whether the media language + matches the query + - ``media_title_match``: whether the media title matches the + query + - ``media_prefix_similarity_rank``: prefix similarity rank + for media results + - ``media_semantic_similarity_rank``: semantic similarity + rank for media results ranking_expression_backend (google.cloud.discoveryengine_v1.types.SearchRequest.RankingExpressionBackend): Optional. The backend to use for the ranking expression evaluation. @@ -427,12 +446,6 @@ class SearchRequest(proto.Message): in the first call. Here, the answer generation happens in the context of the search results from the first search call. - - Multi-turn Search feature is currently at - private GA stage. Please use v1alpha or v1beta - version instead before we launch this feature to - public GA. Or ask for allowlisting through - Google Support team. session_spec (google.cloud.discoveryengine_v1.types.SearchRequest.SessionSpec): Session specification. @@ -461,6 +474,22 @@ class SearchRequest(proto.Message): relevance_score_spec (google.cloud.discoveryengine_v1.types.SearchRequest.RelevanceScoreSpec): Optional. The specification for returning the relevance score. + search_addon_spec (google.cloud.discoveryengine_v1.types.SearchRequest.SearchAddonSpec): + Optional. SearchAddonSpec is used to disable + add-ons for search as per new repricing model. + This field is only supported for search + requests. + custom_ranking_params (google.cloud.discoveryengine_v1.types.SearchRequest.CustomRankingParams): + Optional. Optional configuration for the + Custom Ranking feature. + entity (str): + Optional. The entity for customers that may run multiple + different entities, domains, sites or regions, for example, + "Google US", "Google Ads", "Waymo", "google.com", + "youtube.com", etc. If this is set, it should be exactly + matched with + [UserEvent.entity][google.cloud.discoveryengine.v1.UserEvent.entity] + to get search results boosted by entity. """ class RankingExpressionBackend(proto.Enum): @@ -563,6 +592,14 @@ class DataStoreSpec(proto.Message): used to filter results from workspace data stores. For more information on custom search operators, see `SearchOperators `__. + num_results (int): + Optional. The maximum number of results to retrieve from + this data store. If not specified, it will use the + [SearchRequest.num_results_per_data_store][google.cloud.discoveryengine.v1.SearchRequest.num_results_per_data_store] + if provided, otherwise there is no limit. If both this field + and + [SearchRequest.num_results_per_data_store][google.cloud.discoveryengine.v1.SearchRequest.num_results_per_data_store] + are specified, this field will be used. """ data_store: str = proto.Field( @@ -582,6 +619,10 @@ class DataStoreSpec(proto.Message): proto.STRING, number=7, ) + num_results: int = proto.Field( + proto.INT32, + number=9, + ) class FacetSpec(proto.Message): r"""A facet specification to perform faceted search. @@ -1473,9 +1514,6 @@ class NaturalLanguageQueryUnderstandingSpec(proto.Message): geolocation filters are detected in natural language search queries. Only valid when the FilterExtractionCondition is set to ``ENABLED``. - - If this field is set, it overrides the field names set in - [ServingConfig.geo_search_query_detection_field_names][google.cloud.discoveryengine.v1.ServingConfig.geo_search_query_detection_field_names]. extracted_filter_behavior (google.cloud.discoveryengine_v1.types.SearchRequest.NaturalLanguageQueryUnderstandingSpec.ExtractedFilterBehavior): Optional. Controls behavior of how extracted filters are applied to the search. The default behavior depends on the @@ -1567,11 +1605,22 @@ class ExtractedFilterBehavior(proto.Enum): class SearchAsYouTypeSpec(proto.Message): r"""Specification for search as you type in search requests. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: condition (google.cloud.discoveryengine_v1.types.SearchRequest.SearchAsYouTypeSpec.Condition): The condition under which search as you type should occur. Default to [Condition.DISABLED][google.cloud.discoveryengine.v1.SearchRequest.SearchAsYouTypeSpec.Condition.DISABLED]. + fields (MutableSequence[google.cloud.discoveryengine_v1.types.SearchRequest.SearchAsYouTypeSpec.Field]): + Optional. The list of fields to be used for + Search As You Type scoring. + score_threshold (float): + Optional. Search As You Type score threshold for filtering + purpose. We keep the result if ``score`` >= + ``score_threshold``. + + This field is a member of `oneof`_ ``_score_threshold``. """ class Condition(proto.Enum): @@ -1598,11 +1647,52 @@ class Condition(proto.Enum): ENABLED = 2 AUTO = 3 + class Field(proto.Message): + r"""A schema field to be used for Search As You Type scoring on + this request. Overrides any data-store-level Search As You Type + field configuration for the duration of the request. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + key (str): + Required. A field key that has been indexed + for Search As You Type. + weight (float): + Optional. Weight for scores from this field. + Defaults to 1.0 if not specified. + + This field is a member of `oneof`_ ``_weight``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + weight: float = proto.Field( + proto.DOUBLE, + number=2, + optional=True, + ) + condition: "SearchRequest.SearchAsYouTypeSpec.Condition" = proto.Field( proto.ENUM, number=1, enum="SearchRequest.SearchAsYouTypeSpec.Condition", ) + fields: MutableSequence["SearchRequest.SearchAsYouTypeSpec.Field"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SearchRequest.SearchAsYouTypeSpec.Field", + ) + ) + score_threshold: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) class DisplaySpec(proto.Message): r"""Specifies features for display, like match highlighting. @@ -1698,12 +1788,6 @@ class Mode(proto.Enum): class SessionSpec(proto.Message): r"""Session specification. - Multi-turn Search feature is currently at private GA stage. - Please use v1alpha or v1beta version instead before we launch - this feature to public GA. Or ask for allowlisting through - Google Support team. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: @@ -1754,21 +1838,6 @@ class SessionSpec(proto.Message): optional=True, ) - class RelevanceScoreSpec(proto.Message): - r"""The specification for returning the document relevance score. - - Attributes: - return_relevance_score (bool): - Optional. Whether to return the relevance - score for search results. The higher the score, - the more relevant the document is to the query. - """ - - return_relevance_score: bool = proto.Field( - proto.BOOL, - number=1, - ) - class RelevanceFilterSpec(proto.Message): r"""Relevance filtering specification. @@ -1828,6 +1897,72 @@ class RelevanceThresholdSpec(proto.Message): message="SearchRequest.RelevanceFilterSpec.RelevanceThresholdSpec", ) + class RelevanceScoreSpec(proto.Message): + r"""The specification for returning the document relevance score. + + Attributes: + return_relevance_score (bool): + Optional. Whether to return the relevance + score for search results. The higher the score, + the more relevant the document is to the query. + """ + + return_relevance_score: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class SearchAddonSpec(proto.Message): + r"""SearchAddonSpec is used to disable add-ons for search as per + new repricing model. By default if the SearchAddonSpec is not + specified, we consider that the customer wants to enable them + wherever applicable. + + Attributes: + disable_semantic_add_on (bool): + Optional. If true, semantic add-on is + disabled. Semantic add-on includes embeddings + and jetstream. + disable_kpi_personalization_add_on (bool): + Optional. If true, disables event re-ranking + and personalization to optimize KPIs & + personalize results. + disable_generative_answer_add_on (bool): + Optional. If true, generative answer add-on + is disabled. Generative answer add-on includes + natural language to filters and simple answers. + """ + + disable_semantic_add_on: bool = proto.Field( + proto.BOOL, + number=1, + ) + disable_kpi_personalization_add_on: bool = proto.Field( + proto.BOOL, + number=2, + ) + disable_generative_answer_add_on: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class CustomRankingParams(proto.Message): + r"""Configuration parameters for the Custom Ranking feature. + + Attributes: + expressions_to_precompute (MutableSequence[str]): + Optional. A list of ranking expressions (see + ``ranking_expression`` for the syntax documentation) to + evaluate. The evaluation results will be returned in + ``SearchResponse.SearchResult.rank_signals.precomputed_expression_values`` + field. + """ + + expressions_to_precompute: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + serving_config: str = proto.Field( proto.STRING, number=1, @@ -1870,6 +2005,10 @@ class RelevanceThresholdSpec(proto.Message): number=32, message=DataStoreSpec, ) + num_results_per_data_store: int = proto.Field( + proto.INT32, + number=65, + ) filter: str = proto.Field( proto.STRING, number=7, @@ -1990,6 +2129,20 @@ class RelevanceThresholdSpec(proto.Message): number=52, message=RelevanceScoreSpec, ) + search_addon_spec: SearchAddonSpec = proto.Field( + proto.MESSAGE, + number=62, + message=SearchAddonSpec, + ) + custom_ranking_params: CustomRankingParams = proto.Field( + proto.MESSAGE, + number=64, + message=CustomRankingParams, + ) + entity: str = proto.Field( + proto.STRING, + number=66, + ) class SearchResponse(proto.Message): @@ -2038,6 +2191,9 @@ class SearchResponse(proto.Message): returned if [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1.SearchRequest.ContentSearchSpec.summary_spec] is set. + applied_controls (MutableSequence[str]): + Optional. Controls applied as part of the + Control service. query_expansion_info (google.cloud.discoveryengine_v1.types.SearchResponse.QueryExpansionInfo): Query expansion information for the returned results. @@ -2098,6 +2254,10 @@ class SearchResult(proto.Message): rank_signals (google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult.RankSignals): Optional. A set of ranking signals associated with the result. + retrieval_signals (google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult.RetrievalSignals): + Optional. A set of signals used by the + relevance filter meant for use to fine-tune the + relevance filter thresholds. """ class RankSignals(proto.Message): @@ -2139,6 +2299,10 @@ class RankSignals(proto.Message): Optional. The default rank of the result. custom_signals (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult.RankSignals.CustomSignal]): Optional. A list of custom clearbox signals. + precomputed_expression_values (MutableSequence[float]): + Optional. A list of precomputed expression results for a + given document, in the same order as requested in + ``SearchRequest.custom_ranking_params.expressions_to_precompute``. """ class CustomSignal(proto.Message): @@ -2207,6 +2371,52 @@ class CustomSignal(proto.Message): number=33, message="SearchResponse.SearchResult.RankSignals.CustomSignal", ) + precomputed_expression_values: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=34, + ) + + class RetrievalSignals(proto.Message): + r"""Contains a set of signals used by the relevance filter. + + Attributes: + retrieval_sources (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult.RetrievalSignals.RetrievalSource]): + Optional. Indicates how the result was + retrieved. + semantic_relevance_score (float): + Optional. Relevance score used by the filter when + semantic_relevance_threshold is set. + """ + + class RetrievalSource(proto.Enum): + r"""Indicates the source of the retrieval. + + Values: + RETRIEVAL_SOURCE_UNSPECIFIED (0): + Unspecified retrieval source. + KEYWORD_SEARCH (1): + Indicates the result was retrieved by keyword + search. + SEMANTIC_SEARCH (2): + Indicates the result was retrieved by + semantic search. + """ + + RETRIEVAL_SOURCE_UNSPECIFIED = 0 + KEYWORD_SEARCH = 1 + SEMANTIC_SEARCH = 2 + + retrieval_sources: MutableSequence[ + "SearchResponse.SearchResult.RetrievalSignals.RetrievalSource" + ] = proto.RepeatedField( + proto.ENUM, + number=1, + enum="SearchResponse.SearchResult.RetrievalSignals.RetrievalSource", + ) + semantic_relevance_score: float = proto.Field( + proto.FLOAT, + number=2, + ) id: str = proto.Field( proto.STRING, @@ -2233,6 +2443,11 @@ class CustomSignal(proto.Message): number=7, message="SearchResponse.SearchResult.RankSignals", ) + retrieval_signals: "SearchResponse.SearchResult.RetrievalSignals" = proto.Field( + proto.MESSAGE, + number=11, + message="SearchResponse.SearchResult.RetrievalSignals", + ) class Facet(proto.Message): r"""A facet result. @@ -2988,6 +3203,10 @@ def raw_page(self): number=9, message=Summary, ) + applied_controls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) query_expansion_info: QueryExpansionInfo = proto.Field( proto.MESSAGE, number=14, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py index 4e1e0acd42f2..352347146605 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.20.3" # {x-release-please-version} +__version__ = "0.20.4" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py index 4e1e0acd42f2..352347146605 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.20.3" # {x-release-please-version} +__version__ = "0.20.4" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json index 79463456841c..e3624472b41a 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.20.3" + "version": "0.20.4" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json index afcbf59b0b71..7fe4a951862f 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.20.3" + "version": "0.20.4" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json index d50bf707145a..2c320bbf1511 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.20.3" + "version": "0.20.4" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py index 1e1180a62352..ee8f038337ed 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py @@ -1048,7 +1048,12 @@ def test_search_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/discoveryengine.assist.readwrite", + "https://www.googleapis.com/auth/discoveryengine.readwrite", + "https://www.googleapis.com/auth/discoveryengine.serving.readwrite", + ), scopes=None, default_host="discoveryengine.googleapis.com", ssl_credentials=None, @@ -1085,6 +1090,7 @@ def test_search(request_type, transport: str = "grpc"): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) response = client.search(request) @@ -1102,6 +1108,7 @@ def test_search(request_type, transport: str = "grpc"): assert response.redirect_uri == "redirect_uri_value" assert response.next_page_token == "next_page_token_value" assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] assert ( response.semantic_state == search_service.SearchResponse.SemanticState.DISABLED ) @@ -1130,6 +1137,7 @@ def test_search_non_empty_request_with_auto_populated_field(): user_pseudo_id="user_pseudo_id_value", ranking_expression="ranking_expression_value", session="session_value", + entity="entity_value", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1152,6 +1160,7 @@ def test_search_non_empty_request_with_auto_populated_field(): user_pseudo_id="user_pseudo_id_value", ranking_expression="ranking_expression_value", session="session_value", + entity="entity_value", ) assert args[0] == request_msg @@ -1259,6 +1268,7 @@ async def test_search_async(request_type, transport: str = "grpc_asyncio"): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) ) @@ -1277,6 +1287,7 @@ async def test_search_async(request_type, transport: str = "grpc_asyncio"): assert response.redirect_uri == "redirect_uri_value" assert response.next_page_token == "next_page_token_value" assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] assert ( response.semantic_state == search_service.SearchResponse.SemanticState.DISABLED ) @@ -1568,6 +1579,7 @@ def test_search_lite(request_type, transport: str = "grpc"): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) response = client.search_lite(request) @@ -1585,6 +1597,7 @@ def test_search_lite(request_type, transport: str = "grpc"): assert response.redirect_uri == "redirect_uri_value" assert response.next_page_token == "next_page_token_value" assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] assert ( response.semantic_state == search_service.SearchResponse.SemanticState.DISABLED ) @@ -1613,6 +1626,7 @@ def test_search_lite_non_empty_request_with_auto_populated_field(): user_pseudo_id="user_pseudo_id_value", ranking_expression="ranking_expression_value", session="session_value", + entity="entity_value", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1635,6 +1649,7 @@ def test_search_lite_non_empty_request_with_auto_populated_field(): user_pseudo_id="user_pseudo_id_value", ranking_expression="ranking_expression_value", session="session_value", + entity="entity_value", ) assert args[0] == request_msg @@ -1744,6 +1759,7 @@ async def test_search_lite_async(request_type, transport: str = "grpc_asyncio"): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) ) @@ -1762,6 +1778,7 @@ async def test_search_lite_async(request_type, transport: str = "grpc_asyncio"): assert response.redirect_uri == "redirect_uri_value" assert response.next_page_token == "next_page_token_value" assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] assert ( response.semantic_state == search_service.SearchResponse.SemanticState.DISABLED ) @@ -2562,6 +2579,7 @@ async def test_search_empty_call_grpc_asyncio(): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) ) @@ -2593,6 +2611,7 @@ async def test_search_lite_empty_call_grpc_asyncio(): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) ) @@ -2665,6 +2684,7 @@ def test_search_rest_call_success(request_type): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) @@ -2687,6 +2707,7 @@ def test_search_rest_call_success(request_type): assert response.redirect_uri == "redirect_uri_value" assert response.next_page_token == "next_page_token_value" assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] assert ( response.semantic_state == search_service.SearchResponse.SemanticState.DISABLED ) @@ -2807,6 +2828,7 @@ def test_search_lite_rest_call_success(request_type): redirect_uri="redirect_uri_value", next_page_token="next_page_token_value", corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], semantic_state=search_service.SearchResponse.SemanticState.DISABLED, ) @@ -2829,6 +2851,7 @@ def test_search_lite_rest_call_success(request_type): assert response.redirect_uri == "redirect_uri_value" assert response.next_page_token == "next_page_token_value" assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] assert ( response.semantic_state == search_service.SearchResponse.SemanticState.DISABLED ) @@ -3204,7 +3227,12 @@ def test_search_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/discoveryengine.assist.readwrite", + "https://www.googleapis.com/auth/discoveryengine.readwrite", + "https://www.googleapis.com/auth/discoveryengine.serving.readwrite", + ), quota_project_id="octopus", ) @@ -3230,7 +3258,12 @@ def test_search_service_auth_adc(): SearchServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/discoveryengine.assist.readwrite", + "https://www.googleapis.com/auth/discoveryengine.readwrite", + "https://www.googleapis.com/auth/discoveryengine.serving.readwrite", + ), quota_project_id=None, ) @@ -3250,7 +3283,12 @@ def test_search_service_transport_auth_adc(transport_class): transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/discoveryengine.assist.readwrite", + "https://www.googleapis.com/auth/discoveryengine.readwrite", + "https://www.googleapis.com/auth/discoveryengine.serving.readwrite", + ), quota_project_id="octopus", ) @@ -3303,7 +3341,12 @@ def test_search_service_transport_create_channel(transport_class, grpc_helpers): credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/discoveryengine.assist.readwrite", + "https://www.googleapis.com/auth/discoveryengine.readwrite", + "https://www.googleapis.com/auth/discoveryengine.serving.readwrite", + ), scopes=["1", "2"], default_host="discoveryengine.googleapis.com", ssl_credentials=None, @@ -3632,10 +3675,39 @@ def test_parse_chunk_path(): assert expected == actual -def test_data_store_path(): +def test_control_path(): project = "winkle" location = "nautilus" data_store = "scallop" + control = "abalone" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/controls/{control}".format( + project=project, + location=location, + data_store=data_store, + control=control, + ) + actual = SearchServiceClient.control_path(project, location, data_store, control) + assert expected == actual + + +def test_parse_control_path(): + expected = { + "project": "squid", + "location": "clam", + "data_store": "whelk", + "control": "octopus", + } + path = SearchServiceClient.control_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_control_path(path) + assert expected == actual + + +def test_data_store_path(): + project = "oyster" + location = "nudibranch" + data_store = "cuttlefish" expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format( project=project, location=location, @@ -3647,9 +3719,9 @@ def test_data_store_path(): def test_parse_data_store_path(): expected = { - "project": "abalone", - "location": "squid", - "data_store": "clam", + "project": "mussel", + "location": "winkle", + "data_store": "nautilus", } path = SearchServiceClient.data_store_path(**expected) @@ -3659,11 +3731,11 @@ def test_parse_data_store_path(): def test_document_path(): - project = "whelk" - location = "octopus" - data_store = "oyster" - branch = "nudibranch" - document = "cuttlefish" + project = "scallop" + location = "abalone" + data_store = "squid" + branch = "clam" + document = "whelk" expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format( project=project, location=location, @@ -3679,11 +3751,11 @@ def test_document_path(): def test_parse_document_path(): expected = { - "project": "mussel", - "location": "winkle", - "data_store": "nautilus", - "branch": "scallop", - "document": "abalone", + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + "branch": "cuttlefish", + "document": "mussel", } path = SearchServiceClient.document_path(**expected) @@ -3693,10 +3765,10 @@ def test_parse_document_path(): def test_serving_config_path(): - project = "squid" - location = "clam" - data_store = "whelk" - serving_config = "octopus" + project = "winkle" + location = "nautilus" + data_store = "scallop" + serving_config = "abalone" expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format( project=project, location=location, @@ -3711,10 +3783,10 @@ def test_serving_config_path(): def test_parse_serving_config_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "serving_config": "mussel", + "project": "squid", + "location": "clam", + "data_store": "whelk", + "serving_config": "octopus", } path = SearchServiceClient.serving_config_path(**expected) @@ -3724,10 +3796,10 @@ def test_parse_serving_config_path(): def test_session_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - session = "abalone" + project = "oyster" + location = "nudibranch" + data_store = "cuttlefish" + session = "mussel" expected = "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}".format( project=project, location=location, @@ -3740,10 +3812,10 @@ def test_session_path(): def test_parse_session_path(): expected = { - "project": "squid", - "location": "clam", - "data_store": "whelk", - "session": "octopus", + "project": "winkle", + "location": "nautilus", + "data_store": "scallop", + "session": "abalone", } path = SearchServiceClient.session_path(**expected) @@ -3753,7 +3825,7 @@ def test_parse_session_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3763,7 +3835,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "clam", } path = SearchServiceClient.common_billing_account_path(**expected) @@ -3773,7 +3845,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -3783,7 +3855,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "octopus", } path = SearchServiceClient.common_folder_path(**expected) @@ -3793,7 +3865,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -3803,7 +3875,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "nudibranch", } path = SearchServiceClient.common_organization_path(**expected) @@ -3813,7 +3885,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -3823,7 +3895,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "mussel", } path = SearchServiceClient.common_project_path(**expected) @@ -3833,8 +3905,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -3845,8 +3917,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "scallop", + "location": "abalone", } path = SearchServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-firestore/CHANGELOG.md b/packages/google-cloud-firestore/CHANGELOG.md index f0411a9e9f87..44818488c16f 100644 --- a/packages/google-cloud-firestore/CHANGELOG.md +++ b/packages/google-cloud-firestore/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-firestore/#history +## [2.31.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-firestore-v2.30.0...google-cloud-firestore-v2.31.0) (2026-09-17) + + +### Features + +* **firestore:** add BSONInt32 support ([#18388](https://github.com/googleapis/google-cloud-python/issues/18388)) ([136d4b9](https://github.com/googleapis/google-cloud-python/commit/136d4b95a6231dddfb59c76d2e2a1c5ea7fc84aa)) +* **firestore:** add BSONMinKey and BSONMaxKey support ([#18385](https://github.com/googleapis/google-cloud-python/issues/18385)) ([9a1fb24](https://github.com/googleapis/google-cloud-python/commit/9a1fb24d2b5554a8d34261dc7687b2ec8184f57d)) + ## [2.30.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-firestore-v2.29.0...google-cloud-firestore-v2.30.0) (2026-09-03) diff --git a/packages/google-cloud-firestore/google/cloud/firestore/__init__.py b/packages/google-cloud-firestore/google/cloud/firestore/__init__.py index 47eac898520d..2f770ab9cc4d 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore/__init__.py +++ b/packages/google-cloud-firestore/google/cloud/firestore/__init__.py @@ -35,6 +35,10 @@ AsyncQuery, AsyncTransaction, AsyncWriteBatch, + BSONInt32, + BSONMaxKey, + BSONMinKey, + BSONObjectId, Client, CollectionGroup, CollectionReference, @@ -92,6 +96,10 @@ "async_transactional", "AsyncTransaction", "AsyncWriteBatch", + "BSONInt32", + "BSONMaxKey", + "BSONMinKey", + "BSONObjectId", "Client", "CountAggregation", "CollectionGroup", diff --git a/packages/google-cloud-firestore/google/cloud/firestore/gapic_version.py b/packages/google-cloud-firestore/google/cloud/firestore/gapic_version.py index 399cc4f6e3f3..6361f6d88c72 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore/gapic_version.py +++ b/packages/google-cloud-firestore/google/cloud/firestore/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "2.31.0" # {x-release-please-version} diff --git a/packages/google-cloud-firestore/google/cloud/firestore_admin/gapic_version.py b/packages/google-cloud-firestore/google/cloud/firestore_admin/gapic_version.py index 399cc4f6e3f3..6361f6d88c72 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore_admin/gapic_version.py +++ b/packages/google-cloud-firestore/google/cloud/firestore_admin/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "2.31.0" # {x-release-please-version} diff --git a/packages/google-cloud-firestore/google/cloud/firestore_admin_v1/gapic_version.py b/packages/google-cloud-firestore/google/cloud/firestore_admin_v1/gapic_version.py index 399cc4f6e3f3..6361f6d88c72 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore_admin_v1/gapic_version.py +++ b/packages/google-cloud-firestore/google/cloud/firestore_admin_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "2.31.0" # {x-release-please-version} diff --git a/packages/google-cloud-firestore/google/cloud/firestore_bundle/gapic_version.py b/packages/google-cloud-firestore/google/cloud/firestore_bundle/gapic_version.py index 399cc4f6e3f3..6361f6d88c72 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore_bundle/gapic_version.py +++ b/packages/google-cloud-firestore/google/cloud/firestore_bundle/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "2.31.0" # {x-release-please-version} diff --git a/packages/google-cloud-firestore/google/cloud/firestore_v1/__init__.py b/packages/google-cloud-firestore/google/cloud/firestore_v1/__init__.py index 38593d61832f..f3e87dae3c58 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore_v1/__init__.py +++ b/packages/google-cloud-firestore/google/cloud/firestore_v1/__init__.py @@ -46,6 +46,12 @@ from google.cloud.firestore_v1.base_pipeline import SubPipeline from google.cloud.firestore_v1.base_query import And, FieldFilter, Or from google.cloud.firestore_v1.batch import WriteBatch +from google.cloud.firestore_v1.bson import ( + BSONInt32, + BSONMaxKey, + BSONMinKey, + BSONObjectId, +) from google.cloud.firestore_v1.client import Client from google.cloud.firestore_v1.collection import CollectionReference from google.cloud.firestore_v1.document import DocumentReference @@ -147,6 +153,10 @@ "async_transactional", "AsyncTransaction", "AsyncWriteBatch", + "BSONInt32", + "BSONMaxKey", + "BSONMinKey", + "BSONObjectId", "Client", "CountAggregation", "CollectionGroup", diff --git a/packages/google-cloud-firestore/google/cloud/firestore_v1/_helpers.py b/packages/google-cloud-firestore/google/cloud/firestore_v1/_helpers.py index 04cdd05f0c45..9793c0685121 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore_v1/_helpers.py +++ b/packages/google-cloud-firestore/google/cloud/firestore_v1/_helpers.py @@ -44,6 +44,7 @@ import google from google.cloud import exceptions # type: ignore from google.cloud.firestore_v1 import transforms, types +from google.cloud.firestore_v1.bson import _BSONType from google.cloud.firestore_v1.field_path import FieldPath, parse_field_path from google.cloud.firestore_v1.types import common, document, write from google.cloud.firestore_v1.types.write import DocumentTransform @@ -210,6 +211,9 @@ def encode_value(value) -> types.document.Value: if document_path is not None: return document.Value(reference_value=document_path) + if isinstance(value, _BSONType): + return encode_value(value._to_map_value()) + if isinstance(value, GeoPoint): return document.Value(geo_point_value=value.to_protobuf()) diff --git a/packages/google-cloud-firestore/google/cloud/firestore_v1/bson.py b/packages/google-cloud-firestore/google/cloud/firestore_v1/bson.py new file mode 100644 index 000000000000..b72568413c99 --- /dev/null +++ b/packages/google-cloud-firestore/google/cloud/firestore_v1/bson.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""BSON data types support for Firestore Python SDK. + +This module provides Python representations of BSON data types +for document field serialization in Google Cloud Firestore +according to the official Firestore BSON specification. + +Example: + >>> from google.cloud.firestore_v1.bson import BSONObjectId + >>> doc_data = {"user_id": BSONObjectId("507f191e810c19729de860ea")} +""" + +import abc +import re +from typing import Any, Dict, Union + +__all__ = [ + "BSONObjectId", + "BSONMinKey", + "BSONMaxKey", + "BSONInt32", +] + +_OBJECT_ID_BYTES_LEN = 12 +_HEX_24_REGEX = re.compile(r"^[0-9a-fA-F]{24}$") + + +class _BSONType(abc.ABC): + """Abstract base class for all BSON type containers in Firestore.""" + + __slots__ = () + + @abc.abstractmethod + def _to_map_value(self) -> Any: + """Returns representation for wire serialization. + + Returns: + Any: Map representation dictionary or raw bytes formatted for Firestore. + """ + + @abc.abstractmethod + def __eq__(self, other: Any) -> bool: + """Value equality comparison contract for BSON objects.""" + + @abc.abstractmethod + def __hash__(self) -> int: + """Hash representation contract for set and dictionary keys.""" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + +class BSONObjectId(_BSONType): + """Represents a 12-byte BSON ObjectId identifier. + + Args: + value (Union[str, bytes]): A 24-character hexadecimal string + or 12 raw bytes. + + Raises: + TypeError: If value is not a string or bytes. + ValueError: If string is not a 24-character hex string or bytes length is not 12. + + Example: + >>> oid = BSONObjectId("507f191e810c19729de860ea") + >>> oid.value + '507f191e810c19729de860ea' + """ + + __slots__ = ("_value",) + + def __init__(self, value: Union[str, bytes]): + if isinstance(value, str): + if not _HEX_24_REGEX.match(value): + raise ValueError( + "BSONObjectId string must be a 24-character hex string." + ) + self._value: str = value.lower() + elif isinstance(value, bytes): + if len(value) != _OBJECT_ID_BYTES_LEN: + raise ValueError( + f"BSONObjectId bytes input must be {_OBJECT_ID_BYTES_LEN} raw bytes." + ) + self._value = value.hex() + else: + raise TypeError("BSONObjectId requires str or bytes.") + + @property + def value(self) -> str: + """str: The 24-character lowercase hexadecimal representation.""" + return self._value + + def _to_map_value(self) -> Dict[str, str]: + """Returns legacy map dictionary representation for wire serialization.""" + return {"__oid__": self._value} + + def __repr__(self) -> str: + return f"BSONObjectId('{self._value}')" + + def __str__(self) -> str: + return self._value + + def __eq__(self, other: Any) -> bool: + if isinstance(other, BSONObjectId): + return self._value == other._value + return NotImplemented + + def __hash__(self) -> int: + return hash((type(self), self._value)) + + +class BSONMinKey(_BSONType): + """Represents the BSON MinKey sentinel value for query range boundaries.""" + + __slots__ = () + + def _to_map_value(self) -> Dict[str, None]: + """Returns map dictionary representation for wire serialization.""" + return {"__min__": None} + + def __eq__(self, other: Any) -> bool: + if isinstance(other, BSONMinKey): + return True + return NotImplemented + + def __hash__(self) -> int: + return hash(type(self)) + + +class BSONMaxKey(_BSONType): + """Represents the BSON MaxKey sentinel value for query range boundaries.""" + + __slots__ = () + + def _to_map_value(self) -> Dict[str, None]: + """Returns map dictionary representation for wire serialization.""" + return {"__max__": None} + + def __eq__(self, other: Any) -> bool: + if isinstance(other, BSONMaxKey): + return True + return NotImplemented + + def __hash__(self) -> int: + return hash(type(self)) + + +class BSONInt32(_BSONType): + """Represents a 32-bit signed integer value container for Firestore BSON. + + Args: + value (int): A 32-bit signed integer value. + + Raises: + TypeError: If value is not an integer or is a boolean. + ValueError: If value is outside the 32-bit signed range (-2147483648 to 2147483647). + + Example: + >>> int_val = BSONInt32(42) + >>> int_val.value + 42 + """ + + __slots__ = ("_value",) + + _MIN_INT32: int = -(1 << 31) + _MAX_INT32: int = (1 << 31) - 1 + + def __init__(self, value: int): + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError("BSONInt32 requires an int.") + if not (self._MIN_INT32 <= value <= self._MAX_INT32): + raise ValueError( + f"BSONInt32 value must be between {self._MIN_INT32} and {self._MAX_INT32}." + ) + self._value: int = value + + @property + def value(self) -> int: + """int: The 32-bit signed integer value.""" + return self._value + + def _to_map_value(self) -> Dict[str, int]: + """Returns map dictionary representation for wire serialization.""" + return {"__int__": self._value} + + def __repr__(self) -> str: + return f"BSONInt32({self._value})" + + def __str__(self) -> str: + return str(self._value) + + def __int__(self) -> int: + return self._value + + def __eq__(self, other: Any) -> bool: + if isinstance(other, BSONInt32): + return self._value == other._value + return NotImplemented + + def __hash__(self) -> int: + return hash((type(self), self._value)) diff --git a/packages/google-cloud-firestore/google/cloud/firestore_v1/gapic_version.py b/packages/google-cloud-firestore/google/cloud/firestore_v1/gapic_version.py index 399cc4f6e3f3..6361f6d88c72 100644 --- a/packages/google-cloud-firestore/google/cloud/firestore_v1/gapic_version.py +++ b/packages/google-cloud-firestore/google/cloud/firestore_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "2.31.0" # {x-release-please-version} diff --git a/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.admin.v1.json b/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.admin.v1.json index c3d223a4b501..7abd0bdc099f 100644 --- a/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.admin.v1.json +++ b/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.admin.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-firestore", - "version": "2.30.0" + "version": "2.31.0" }, "snippets": [ { diff --git a/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.v1.json b/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.v1.json index 4885bacd82a1..ad05c840314b 100644 --- a/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.v1.json +++ b/packages/google-cloud-firestore/samples/generated_samples/snippet_metadata_google.firestore.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-firestore", - "version": "2.30.0" + "version": "2.31.0" }, "snippets": [ { diff --git a/packages/google-cloud-firestore/tests/system/test_system.py b/packages/google-cloud-firestore/tests/system/test_system.py index 1e6ffca06e9a..f523d126ac1b 100644 --- a/packages/google-cloud-firestore/tests/system/test_system.py +++ b/packages/google-cloud-firestore/tests/system/test_system.py @@ -48,6 +48,12 @@ from google.cloud import firestore_v1 as firestore from google.cloud.firestore_v1.base_query import And, FieldFilter, Or from google.cloud.firestore_v1.base_vector_query import DistanceMeasure +from google.cloud.firestore_v1.bson import ( + BSONInt32, + BSONMaxKey, + BSONMinKey, + BSONObjectId, +) from google.cloud.firestore_v1.vector import Vector @@ -1274,6 +1280,32 @@ def test_unicode_doc(client, cleanup, database): assert snapshot2.reference.id == explicit_doc_id +@pytest.mark.parametrize("database", [FIRESTORE_ENTERPRISE_DB], indirect=True) +def test_bson_document_writes(client, cleanup, database): + """Test write operations for BSON types on Enterprise DB.""" + collection_id = "bson_type_writes_" + UNIQUE_RESOURCE_ID + doc_ref = client.collection(collection_id).document("bson_doc") + cleanup(doc_ref.delete) + + bson_payload = { + "user_id": BSONObjectId("507f191e810c19729de860ea"), + "min_key": BSONMinKey(), + "max_key": BSONMaxKey(), + "int32_val": BSONInt32(42), + } + + doc_ref.set(bson_payload) + + snapshot = doc_ref.get() + assert snapshot.exists + assert snapshot.to_dict() == { + "user_id": {"__oid__": "507f191e810c19729de860ea"}, + "min_key": {"__min__": None}, + "max_key": {"__max__": None}, + "int32_val": {"__int__": 42}, + } + + @pytest.fixture(scope="module") def query_docs(client, database): collection_id = "qs" + UNIQUE_RESOURCE_ID diff --git a/packages/google-cloud-firestore/tests/system/test_system_async.py b/packages/google-cloud-firestore/tests/system/test_system_async.py index ac2451043cef..aca145362692 100644 --- a/packages/google-cloud-firestore/tests/system/test_system_async.py +++ b/packages/google-cloud-firestore/tests/system/test_system_async.py @@ -51,6 +51,12 @@ from google.cloud import firestore_v1 as firestore from google.cloud.firestore_v1.base_query import And, FieldFilter, Or from google.cloud.firestore_v1.base_vector_query import DistanceMeasure +from google.cloud.firestore_v1.bson import ( + BSONInt32, + BSONMaxKey, + BSONMinKey, + BSONObjectId, +) from google.cloud.firestore_v1.query_profile import ( ExecutionStats, ExplainMetrics, @@ -1246,6 +1252,33 @@ async def test_list_collections_with_read_time(client, cleanup, database): } +@pytest.mark.asyncio +@pytest.mark.parametrize("database", [FIRESTORE_ENTERPRISE_DB], indirect=True) +async def test_async_bson_document_writes(client, cleanup, database): + """Test async write operations for BSON types on Enterprise DB.""" + collection_id = "async_bson_type_writes_" + UNIQUE_RESOURCE_ID + doc_ref = client.collection(collection_id).document("bson_doc") + cleanup(doc_ref.delete) + + bson_payload = { + "user_id": BSONObjectId("507f191e810c19729de860ea"), + "min_key": BSONMinKey(), + "max_key": BSONMaxKey(), + "int32_val": BSONInt32(42), + } + + await doc_ref.set(bson_payload) + + snapshot = await doc_ref.get() + assert snapshot.exists + assert snapshot.to_dict() == { + "user_id": {"__oid__": "507f191e810c19729de860ea"}, + "min_key": {"__min__": None}, + "max_key": {"__max__": None}, + "int32_val": {"__int__": 42}, + } + + @pytest_asyncio.fixture(scope="module") async def query_docs(client): collection_id = "qs" + UNIQUE_RESOURCE_ID diff --git a/packages/google-cloud-firestore/tests/unit/v1/test_bson.py b/packages/google-cloud-firestore/tests/unit/v1/test_bson.py new file mode 100644 index 000000000000..06a85244e727 --- /dev/null +++ b/packages/google-cloud-firestore/tests/unit/v1/test_bson.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Unit tests for google.cloud.firestore_v1.bson classes.""" + +import copy +import pickle + +import pytest + +from google.cloud.firestore_v1.bson import ( + BSONInt32, + BSONMaxKey, + BSONMinKey, + BSONObjectId, + _BSONType, +) + + +def test_bson_type_abc_cannot_be_instantiated(): + with pytest.raises(TypeError): + _BSONType() # type: ignore + + +def test_bson_type_inheritance(): + oid = BSONObjectId("507f191e810c19729de860ea") + assert isinstance(oid, _BSONType) + + +def test_bson_object_id_from_hex_string(): + hex_str = "507f191e810c19729de860ea" + oid = BSONObjectId(hex_str) + assert oid.value == hex_str + + +def test_bson_object_id_from_uppercase_hex_string(): + oid = BSONObjectId("507F191E810C19729DE860EA") + assert oid.value == "507f191e810c19729de860ea" + + +def test_bson_object_id_from_bytes(): + raw_bytes = b"\x50\x7f\x19\x1e\x81\x0c\x19\x72\x9d\xe8\x60\xea" + oid = BSONObjectId(raw_bytes) + assert oid.value == "507f191e810c19729de860ea" + + +def test_bson_object_id_to_map_value(): + hex_str = "507f191e810c19729de860ea" + oid = BSONObjectId(hex_str) + assert oid._to_map_value() == {"__oid__": hex_str} + + +@pytest.mark.parametrize( + "invalid_input, exc_type, match_msg", + [ + ("invalid_hex", ValueError, "24-character hex string"), + (b"short", ValueError, "12 raw bytes"), + (bytearray(b"\x50" * 12), TypeError, "requires str or bytes"), + (12345, TypeError, "requires str or bytes"), + (None, TypeError, "requires str or bytes"), + ], +) +def test_bson_object_id_invalid_inputs(invalid_input, exc_type, match_msg): + with pytest.raises(exc_type, match=match_msg): + BSONObjectId(invalid_input) + + +def test_bson_object_id_equality(): + oid1 = BSONObjectId("507f191e810c19729de860ea") + oid2 = BSONObjectId("507f191e810c19729de860ea") + oid3 = BSONObjectId("507f191e810c19729de860eb") + + assert oid1 == oid2 + assert oid1 != oid3 + assert oid1 != "507f191e810c19729de860ea" + + +def test_bson_object_id_equality_not_implemented(): + oid = BSONObjectId("507f191e810c19729de860ea") + + class CooperativeOther: + def __eq__(self, other): + return True + + assert oid == CooperativeOther() + + +def test_bson_object_id_hash_and_dict_key(): + oid1 = BSONObjectId("507f191e810c19729de860ea") + oid2 = BSONObjectId("507f191e810c19729de860ea") + + assert hash(oid1) == hash(oid2) + lookup = {oid1: "success"} + assert lookup[oid2] == "success" + assert len({oid1, oid2}) == 1 + + +def test_bson_object_id_repr(): + oid = BSONObjectId("507f191e810c19729de860ea") + assert repr(oid) == "BSONObjectId('507f191e810c19729de860ea')" + + +def test_bson_object_id_str(): + oid = BSONObjectId("507f191e810c19729de860ea") + assert str(oid) == "507f191e810c19729de860ea" + + +def test_bson_object_id_copy(): + oid = BSONObjectId("507f191e810c19729de860ea") + assert copy.copy(oid) == oid + assert copy.deepcopy(oid) == oid + + +def test_bson_object_id_pickle(): + oid = BSONObjectId("507f191e810c19729de860ea") + unpickled = pickle.loads(pickle.dumps(oid)) + assert unpickled == oid + assert unpickled.value == oid.value + + +def test_bson_minkey_to_map_value(): + assert BSONMinKey()._to_map_value() == {"__min__": None} + + +def test_bson_minkey_equality(): + key1 = BSONMinKey() + key2 = BSONMinKey() + assert key1 == key2 + assert key1 != BSONMaxKey() + assert key1 != "min" + + +def test_bson_minkey_hash_and_dict_key(): + key1 = BSONMinKey() + key2 = BSONMinKey() + assert hash(key1) == hash(key2) + assert len({key1, key2}) == 1 + + +def test_bson_minkey_repr(): + assert repr(BSONMinKey()) == "BSONMinKey()" + + +def test_bson_minkey_copy(): + key = BSONMinKey() + assert copy.copy(key) == key + assert copy.deepcopy(key) == key + + +def test_bson_minkey_pickle(): + key = BSONMinKey() + assert pickle.loads(pickle.dumps(key)) == key + + +def test_bson_maxkey_to_map_value(): + assert BSONMaxKey()._to_map_value() == {"__max__": None} + + +def test_bson_maxkey_equality(): + key1 = BSONMaxKey() + key2 = BSONMaxKey() + assert key1 == key2 + assert key1 != BSONMinKey() + assert key1 != "max" + + +def test_bson_maxkey_hash_and_dict_key(): + key1 = BSONMaxKey() + key2 = BSONMaxKey() + assert hash(key1) == hash(key2) + assert len({key1, key2}) == 1 + + +def test_bson_maxkey_repr(): + assert repr(BSONMaxKey()) == "BSONMaxKey()" + + +def test_bson_maxkey_copy(): + key = BSONMaxKey() + assert copy.copy(key) == key + assert copy.deepcopy(key) == key + + +def test_bson_maxkey_pickle(): + key = BSONMaxKey() + assert pickle.loads(pickle.dumps(key)) == key + + +def test_bson_int32_valid(): + val = BSONInt32(42) + assert val.value == 42 + assert int(val) == 42 + assert str(val) == "42" + assert repr(val) == "BSONInt32(42)" + assert val._to_map_value() == {"__int__": 42} + + +def test_bson_int32_boundaries(): + min_val = BSONInt32(-2147483648) + max_val = BSONInt32(2147483647) + assert min_val.value == -2147483648 + assert max_val.value == 2147483647 + + +@pytest.mark.parametrize( + "invalid_input, exc_type, match_msg", + [ + (2147483648, ValueError, "between -2147483648 and 2147483647"), + (-2147483649, ValueError, "between -2147483648 and 2147483647"), + ("42", TypeError, "requires an int"), + (42.0, TypeError, "requires an int"), + (True, TypeError, "requires an int"), + (False, TypeError, "requires an int"), + (None, TypeError, "requires an int"), + ], +) +def test_bson_int32_invalid(invalid_input, exc_type, match_msg): + with pytest.raises(exc_type, match=match_msg): + BSONInt32(invalid_input) + + +def test_bson_int32_equality(): + val1 = BSONInt32(42) + val2 = BSONInt32(42) + val3 = BSONInt32(100) + + assert val1 == val2 + assert val1 != val3 + assert val1 != 42 # BSONInt32 is not equal to plain int + + class CooperativeOther: + def __eq__(self, other): + return True + + assert val1 == CooperativeOther() + + +def test_bson_int32_hash_and_dict_key(): + val1 = BSONInt32(42) + val2 = BSONInt32(42) + + assert hash(val1) == hash(val2) + assert hash(val1) != hash(42) + lookup = {val1: "success"} + assert lookup[val2] == "success" + assert len({val1, val2}) == 1 + + +def test_bson_int32_copy(): + val = BSONInt32(42) + assert copy.copy(val) == val + assert copy.deepcopy(val) == val + + +def test_bson_int32_pickle(): + val = BSONInt32(42) + assert pickle.loads(pickle.dumps(val)) == val diff --git a/packages/google-cloud-kms/CHANGELOG.md b/packages/google-cloud-kms/CHANGELOG.md index 819709005334..36ec965e6b67 100644 --- a/packages/google-cloud-kms/CHANGELOG.md +++ b/packages/google-cloud-kms/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-kms/#history +## [3.17.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-kms-v3.16.0...google-cloud-kms-v3.17.0) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [3.16.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-kms-v3.15.0...google-cloud-kms-v3.16.0) (2026-07-16) diff --git a/packages/google-cloud-kms/google/cloud/kms/gapic_version.py b/packages/google-cloud-kms/google/cloud/kms/gapic_version.py index b33afb1709fe..90f48790f969 100644 --- a/packages/google-cloud-kms/google/cloud/kms/gapic_version.py +++ b/packages/google-cloud-kms/google/cloud/kms/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.16.0" # {x-release-please-version} +__version__ = "3.17.0" # {x-release-please-version} diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py index b33afb1709fe..90f48790f969 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.16.0" # {x-release-please-version} +__version__ = "3.17.0" # {x-release-please-version} diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py index c75fe5ea4b91..34287186ef85 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -109,6 +109,10 @@ class KeyManagementServiceAsyncClient: parse_crypto_key_version_path = staticmethod( KeyManagementServiceClient.parse_crypto_key_version_path ) + ekm_connection_path = staticmethod(KeyManagementServiceClient.ekm_connection_path) + parse_ekm_connection_path = staticmethod( + KeyManagementServiceClient.parse_ekm_connection_path + ) import_job_path = staticmethod(KeyManagementServiceClient.import_job_path) parse_import_job_path = staticmethod( KeyManagementServiceClient.parse_import_job_path diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index 13dc2560d07e..46bc159e5df0 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -245,6 +245,28 @@ def parse_crypto_key_version_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def ekm_connection_path( + project: str, + location: str, + ekm_connection: str, + ) -> str: + """Returns a fully-qualified ekm_connection string.""" + return "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( + project=project, + location=location, + ekm_connection=ekm_connection, + ) + + @staticmethod + def parse_ekm_connection_path(path: str) -> Dict[str, str]: + """Parses a ekm_connection path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/ekmConnections/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def import_job_path( project: str, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py index baeb205f6d98..0258620488c6 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py @@ -1644,14 +1644,25 @@ class ExternalProtectionLevelOptions(proto.Message): Attributes: external_key_uri (str): - The URI for an external resource that this + Optional. The URI for an external resource that this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents. ekm_connection_key_path (str): - The path to the external key material on the EKM when using + Optional. The path to the external key material on the EKM + when using [EkmConnection][google.cloud.kms.v1.EkmConnection] e.g., "v0/my/key". Set this field instead of external_key_uri when using an [EkmConnection][google.cloud.kms.v1.EkmConnection]. + ekm_connection_backend_override (str): + Optional. The resource name of the backend environment where + the key material of + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] is + associated with. Setting this field overrides the + [CryptoKeyBackend][]. This field may be set when + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] is + set to + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC]. + Format: ``projects/*/locations/*/ekmConnections/*``. """ external_key_uri: str = proto.Field( @@ -1662,6 +1673,10 @@ class ExternalProtectionLevelOptions(proto.Message): proto.STRING, number=2, ) + ekm_connection_backend_override: str = proto.Field( + proto.STRING, + number=3, + ) class KeyAccessJustificationsPolicy(proto.Message): diff --git a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json index 3065c3bbc483..6bfc82adcfa4 100644 --- a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json +++ b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-kms", - "version": "3.16.0" + "version": "3.17.0" }, "snippets": [ { diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py index ea2ca88ea452..d43bacb5853b 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -24141,6 +24141,7 @@ def test_create_crypto_key_rest_call_success(request_type): "external_protection_level_options": { "external_key_uri": "external_key_uri_value", "ekm_connection_key_path": "ekm_connection_key_path_value", + "ekm_connection_backend_override": "ekm_connection_backend_override_value", }, "reimport_eligible": True, "trusted_wrapping_enabled": True, @@ -24395,6 +24396,7 @@ def test_create_crypto_key_version_rest_call_success(request_type): "external_protection_level_options": { "external_key_uri": "external_key_uri_value", "ekm_connection_key_path": "ekm_connection_key_path_value", + "ekm_connection_backend_override": "ekm_connection_backend_override_value", }, "reimport_eligible": True, "trusted_wrapping_enabled": True, @@ -25648,6 +25650,7 @@ def test_update_crypto_key_rest_call_success(request_type): "external_protection_level_options": { "external_key_uri": "external_key_uri_value", "ekm_connection_key_path": "ekm_connection_key_path_value", + "ekm_connection_backend_override": "ekm_connection_backend_override_value", }, "reimport_eligible": True, "trusted_wrapping_enabled": True, @@ -25906,6 +25909,7 @@ def test_update_crypto_key_version_rest_call_success(request_type): "external_protection_level_options": { "external_key_uri": "external_key_uri_value", "ekm_connection_key_path": "ekm_connection_key_path_value", + "ekm_connection_backend_override": "ekm_connection_backend_override_value", }, "reimport_eligible": True, "trusted_wrapping_enabled": True, @@ -29760,11 +29764,39 @@ def test_parse_crypto_key_version_path(): assert expected == actual -def test_import_job_path(): +def test_ekm_connection_path(): project = "cuttlefish" location = "mussel" - key_ring = "winkle" - import_job = "nautilus" + ekm_connection = "winkle" + expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( + project=project, + location=location, + ekm_connection=ekm_connection, + ) + actual = KeyManagementServiceClient.ekm_connection_path( + project, location, ekm_connection + ) + assert expected == actual + + +def test_parse_ekm_connection_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "ekm_connection": "abalone", + } + path = KeyManagementServiceClient.ekm_connection_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_ekm_connection_path(path) + assert expected == actual + + +def test_import_job_path(): + project = "squid" + location = "clam" + key_ring = "whelk" + import_job = "octopus" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format( project=project, location=location, @@ -29779,10 +29811,10 @@ def test_import_job_path(): def test_parse_import_job_path(): expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "import_job": "clam", + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "import_job": "mussel", } path = KeyManagementServiceClient.import_job_path(**expected) @@ -29792,9 +29824,9 @@ def test_parse_import_job_path(): def test_key_ring_path(): - project = "whelk" - location = "octopus" - key_ring = "oyster" + project = "winkle" + location = "nautilus" + key_ring = "scallop" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format( project=project, location=location, @@ -29806,9 +29838,9 @@ def test_key_ring_path(): def test_parse_key_ring_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "key_ring": "mussel", + "project": "abalone", + "location": "squid", + "key_ring": "clam", } path = KeyManagementServiceClient.key_ring_path(**expected) @@ -29818,11 +29850,11 @@ def test_parse_key_ring_path(): def test_public_key_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" + project = "whelk" + location = "octopus" + key_ring = "oyster" + crypto_key = "nudibranch" + crypto_key_version = "cuttlefish" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format( project=project, location=location, @@ -29838,11 +29870,11 @@ def test_public_key_path(): def test_parse_public_key_path(): expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", + "project": "mussel", + "location": "winkle", + "key_ring": "nautilus", + "crypto_key": "scallop", + "crypto_key_version": "abalone", } path = KeyManagementServiceClient.public_key_path(**expected) @@ -29852,9 +29884,9 @@ def test_parse_public_key_path(): def test_retired_resource_path(): - project = "cuttlefish" - location = "mussel" - retired_resource = "winkle" + project = "squid" + location = "clam" + retired_resource = "whelk" expected = "projects/{project}/locations/{location}/retiredResources/{retired_resource}".format( project=project, location=location, @@ -29868,9 +29900,9 @@ def test_retired_resource_path(): def test_parse_retired_resource_path(): expected = { - "project": "nautilus", - "location": "scallop", - "retired_resource": "abalone", + "project": "octopus", + "location": "oyster", + "retired_resource": "nudibranch", } path = KeyManagementServiceClient.retired_resource_path(**expected) @@ -29880,7 +29912,7 @@ def test_parse_retired_resource_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -29890,7 +29922,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "mussel", } path = KeyManagementServiceClient.common_billing_account_path(**expected) @@ -29900,7 +29932,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "winkle" expected = "folders/{folder}".format( folder=folder, ) @@ -29910,7 +29942,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "nautilus", } path = KeyManagementServiceClient.common_folder_path(**expected) @@ -29920,7 +29952,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "scallop" expected = "organizations/{organization}".format( organization=organization, ) @@ -29930,7 +29962,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "abalone", } path = KeyManagementServiceClient.common_organization_path(**expected) @@ -29940,7 +29972,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "squid" expected = "projects/{project}".format( project=project, ) @@ -29950,7 +29982,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "clam", } path = KeyManagementServiceClient.common_project_path(**expected) @@ -29960,8 +29992,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -29972,8 +30004,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "oyster", + "location": "nudibranch", } path = KeyManagementServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-network-services/CHANGELOG.md b/packages/google-cloud-network-services/CHANGELOG.md index 5db9982e6ed9..318e0182e99a 100644 --- a/packages/google-cloud-network-services/CHANGELOG.md +++ b/packages/google-cloud-network-services/CHANGELOG.md @@ -4,6 +4,18 @@ [1]: https://pypi.org/project/google-cloud-network-services/#history +## [0.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-services-v0.10.2...google-cloud-network-services-v0.10.3) (2026-09-17) + + +### Features + +* **google/cloud/networkservices/v1beta1:** add google-cloud-network-services ([#18398](https://github.com/googleapis/google-cloud-python/issues/18398)) ([8df34ce](https://github.com/googleapis/google-cloud-python/commit/8df34cee63a12075c5a7334a39e6852439655151)) + + +### Bug Fixes + +* empty commit to bump v1beta version ([#18411](https://github.com/googleapis/google-cloud-python/issues/18411)) ([3b3cc6f](https://github.com/googleapis/google-cloud-python/commit/3b3cc6f3deda911aeff9163f662ff56c19d04aed)) + ## [0.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-services-v0.10.1...google-cloud-network-services-v0.10.2) (2026-08-06) diff --git a/packages/google-cloud-network-services/docs/index.rst b/packages/google-cloud-network-services/docs/index.rst index 88cf30851edc..ac6b597fa86e 100644 --- a/packages/google-cloud-network-services/docs/index.rst +++ b/packages/google-cloud-network-services/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Network Services. +By default, you will get version ``network_services_v1``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference network_services_v1/services_ network_services_v1/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + network_services_v1beta1/services_ + network_services_v1beta1/types_ + Changelog --------- diff --git a/packages/google-cloud-network-services/docs/network_services_v1beta1/dep_service.rst b/packages/google-cloud-network-services/docs/network_services_v1beta1/dep_service.rst new file mode 100644 index 000000000000..ce87504ebb04 --- /dev/null +++ b/packages/google-cloud-network-services/docs/network_services_v1beta1/dep_service.rst @@ -0,0 +1,10 @@ +DepService +---------------------------- + +.. automodule:: google.cloud.network_services_v1beta1.services.dep_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_services_v1beta1.services.dep_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-network-services/docs/network_services_v1beta1/network_services.rst b/packages/google-cloud-network-services/docs/network_services_v1beta1/network_services.rst new file mode 100644 index 000000000000..d709fabaa578 --- /dev/null +++ b/packages/google-cloud-network-services/docs/network_services_v1beta1/network_services.rst @@ -0,0 +1,10 @@ +NetworkServices +--------------------------------- + +.. automodule:: google.cloud.network_services_v1beta1.services.network_services + :members: + :inherited-members: + +.. automodule:: google.cloud.network_services_v1beta1.services.network_services.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-network-services/docs/network_services_v1beta1/services_.rst b/packages/google-cloud-network-services/docs/network_services_v1beta1/services_.rst new file mode 100644 index 000000000000..d9be6c53ec02 --- /dev/null +++ b/packages/google-cloud-network-services/docs/network_services_v1beta1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Network Services v1beta1 API +====================================================== +.. toctree:: + :maxdepth: 2 + + dep_service + network_services diff --git a/packages/google-cloud-network-services/docs/network_services_v1beta1/types_.rst b/packages/google-cloud-network-services/docs/network_services_v1beta1/types_.rst new file mode 100644 index 000000000000..ff4936f356cc --- /dev/null +++ b/packages/google-cloud-network-services/docs/network_services_v1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Network Services v1beta1 API +=================================================== + +.. automodule:: google.cloud.network_services_v1beta1.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py b/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py index d0c6015ceaf2..a37a7120a0ba 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py +++ b/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.2" # {x-release-please-version} +__version__ = "0.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_version.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_version.py index d0c6015ceaf2..a37a7120a0ba 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_version.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.2" # {x-release-please-version} +__version__ = "0.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/__init__.py new file mode 100644 index 000000000000..ecf05ab8ccd1 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/__init__.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import google.api_core as api_core + +from google.cloud.network_services_v1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__ = { + "google.cloud.network_services_v1beta1.services.dep_service", + "google.cloud.network_services_v1beta1.services.network_services", + "google.cloud.network_services_v1beta1.types.common", + "google.cloud.network_services_v1beta1.types.dep", + "google.cloud.network_services_v1beta1.types.endpoint_policy", + "google.cloud.network_services_v1beta1.types.network_services", +} + + +from .services.dep_service import DepServiceAsyncClient, DepServiceClient +from .services.network_services import NetworkServicesAsyncClient, NetworkServicesClient +from .types.common import EndpointMatcher, OperationMetadata, TrafficPortSelector +from .types.dep import ( + CreateExtensionBindingRequest, + CreateLbRouteExtensionRequest, + CreateLbTrafficExtensionRequest, + DeleteExtensionBindingRequest, + DeleteLbRouteExtensionRequest, + DeleteLbTrafficExtensionRequest, + EventType, + ExtensionBinding, + ExtensionChain, + GetExtensionBindingRequest, + GetLbRouteExtensionRequest, + GetLbTrafficExtensionRequest, + LbRouteExtension, + LbTrafficExtension, + ListExtensionBindingsRequest, + ListExtensionBindingsResponse, + ListLbRouteExtensionsRequest, + ListLbRouteExtensionsResponse, + ListLbTrafficExtensionsRequest, + ListLbTrafficExtensionsResponse, + LoadBalancingScheme, + UpdateExtensionBindingRequest, + UpdateLbRouteExtensionRequest, + UpdateLbTrafficExtensionRequest, +) +from .types.endpoint_policy import ( + CreateEndpointPolicyRequest, + DeleteEndpointPolicyRequest, + EndpointPolicy, + GetEndpointPolicyRequest, + ListEndpointPoliciesRequest, + ListEndpointPoliciesResponse, + UpdateEndpointPolicyRequest, +) + +__all__ = ( + "DepServiceAsyncClient", + "NetworkServicesAsyncClient", + "CreateEndpointPolicyRequest", + "CreateExtensionBindingRequest", + "CreateLbRouteExtensionRequest", + "CreateLbTrafficExtensionRequest", + "DeleteEndpointPolicyRequest", + "DeleteExtensionBindingRequest", + "DeleteLbRouteExtensionRequest", + "DeleteLbTrafficExtensionRequest", + "DepServiceClient", + "EndpointMatcher", + "EndpointPolicy", + "EventType", + "ExtensionBinding", + "ExtensionChain", + "GetEndpointPolicyRequest", + "GetExtensionBindingRequest", + "GetLbRouteExtensionRequest", + "GetLbTrafficExtensionRequest", + "LbRouteExtension", + "LbTrafficExtension", + "ListEndpointPoliciesRequest", + "ListEndpointPoliciesResponse", + "ListExtensionBindingsRequest", + "ListExtensionBindingsResponse", + "ListLbRouteExtensionsRequest", + "ListLbRouteExtensionsResponse", + "ListLbTrafficExtensionsRequest", + "ListLbTrafficExtensionsResponse", + "LoadBalancingScheme", + "NetworkServicesClient", + "OperationMetadata", + "TrafficPortSelector", + "UpdateEndpointPolicyRequest", + "UpdateExtensionBindingRequest", + "UpdateLbRouteExtensionRequest", + "UpdateLbTrafficExtensionRequest", +) + +api_core.check_python_version("google.cloud.network_services_v1beta1") +api_core.check_dependency_versions("google.cloud.network_services_v1beta1") diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/_compat.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/_compat.py new file mode 100644 index 000000000000..3d3bdf9e2c91 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/_compat.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""A compatibility module for older versions of google-api-core.""" + +import json +import os +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import urlparse, urlunparse + +from google.api_core import path_template +from google.api_core.universe import EmptyUniverseError +from google.auth.exceptions import MutualTLSChannelError +from google.protobuf import json_format + +try: + # note: `#type: ignore` is added because the return type for `should_use_client_cert` + # is different than that of the fallback implementation below. This will be removed once + # we bump the minimum supported version of google-auth. + from google.auth.transport.mtls import should_use_client_cert # type: ignore +except ImportError: # pragma: NO COVER + + def should_use_client_cert(): + """Returns whether client certificate should be used for mTLS.""" + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert == "true" + + +def read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`," + " `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + +DEFAULT_UNIVERSE = "googleapis.com" + +try: + from google.api_core.universe import get_default_mtls_endpoint +except ImportError: # pragma: NO COVER + + def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Other URLs (including those that do not match these domain suffixes or + already contain '.mtls.') are passed through as-is. + + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint or ".mtls." in api_endpoint.lower(): + return api_endpoint + + has_scheme = "://" in api_endpoint + if not has_scheme: + parsed = urlparse("//" + api_endpoint) + else: + parsed = urlparse(api_endpoint) + + host = parsed.hostname + if not host: + return api_endpoint + + port = f":{parsed.port}" if parsed.port else "" + + lowered_host = host.lower() + suffix_sandbox = ".sandbox.googleapis.com" + suffix_google = ".googleapis.com" + if lowered_host.endswith(suffix_sandbox): + new_host = host[: -len(suffix_sandbox)] + ".mtls.sandbox.googleapis.com" + elif lowered_host.endswith(suffix_google): + new_host = host[: -len(suffix_google)] + ".mtls.googleapis.com" + else: + return api_endpoint + + netloc = new_host + port + new_parsed = parsed._replace(netloc=netloc) + + if not has_scheme: + return urlunparse(new_parsed)[2:] + else: + return urlunparse(new_parsed) + + +try: + from google.api_core.universe import get_api_endpoint +except ImportError: # pragma: NO COVER + + def get_api_endpoint( + api_override: Optional[str], + universe_domain: str, + default_universe: str, + default_mtls_endpoint: Optional[str], + default_endpoint_template: str, + use_mtls: bool, + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (Optional[str]): The API endpoint override. If specified, + this is always returned. + universe_domain (str): The universe domain used by the client. + default_universe (str): The default universe domain. + default_mtls_endpoint (Optional[str]): The default mTLS endpoint. + default_endpoint_template (str): The default endpoint template containing + a placeholder `{UNIVERSE_DOMAIN}`. + use_mtls (bool): Whether to use the mTLS endpoint. + + Returns: + str: The API endpoint to be used by the client. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mTLS is requested but + not supported in the configured universe domain. + ValueError: If mTLS is requested but no mTLS endpoint is available. + """ + if api_override is not None: + return api_override + + if use_mtls: + if universe_domain.lower() != default_universe.lower(): + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {default_universe}." + ) + if not default_mtls_endpoint: + raise ValueError("mTLS endpoint is not available.") + return default_mtls_endpoint + else: + return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + + +try: + from google.api_core.universe import get_universe_domain +except ImportError: # pragma: NO COVER + + def get_universe_domain( + *potential_universes: Optional[str], + default_universe: str, + ) -> str: + """Return the universe domain used by the client. + + Args: + *potential_universes (Optional[str]): Potential universe domains in order of preference. + default_universe (str): The default universe domain. + + Returns: + str: The universe domain to be used by the client. + + Raises: + EmptyUniverseError: If the resolved universe domain is an empty string. + """ + resolved = next( + (x.strip() for x in potential_universes if x is not None), + default_universe, + ) + + if not resolved: + raise EmptyUniverseError() + return resolved + + +try: + from google.api_core.rest_helpers import transcode_request # type: ignore +except ImportError: # pragma: NO COVER + + def transcode_request( + http_options: List[Dict[str, str]], + request: Any, + required_fields_default_values: Optional[Dict[str, Any]] = None, + rest_numeric_enums: bool = False, + ) -> Tuple[Dict[str, Any], Optional[str], Dict[str, Any]]: + """Transcodes a request into HTTP method, URI, body, and query parameters. + + Args: + http_options (List[Dict[str, str]]): List of HTTP transcoding rules. + request (Any): The protobuf or proto-plus request message. + required_fields_default_values (Optional[Dict[str, Any]]): Dictionary + of required fields default values to merge into query parameters if missing. + rest_numeric_enums (bool): Whether to encode enums as integers. + + Returns: + Tuple[Dict[str, Any], Optional[str], Dict[str, Any]]: A tuple containing: + - The raw transcoded request dictionary (containing keys like 'uri', 'method'). + - The serialized request body JSON string, or None if no body. + - The query parameters dictionary. + """ + if request is None: + raise TypeError("request cannot be None") + + # Convert proto-plus message to its underlying protobuf message if needed + pb_request = getattr(request, "_pb", request) + + transcoded_request = path_template.transcode(http_options, pb_request) + + body_json = None + if transcoded_request.get("body") is not None: + body_json = json_format.MessageToJson( + transcoded_request["body"], + use_integers_for_enums=rest_numeric_enums, + ) + + query_params_json = {} + if transcoded_request.get("query_params") is not None: + query_params_json = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=rest_numeric_enums, + ) + ) + + # If required_fields_default_values is provided, we merge default values for missing + # required fields into the query parameters. + if required_fields_default_values: + for k, v in required_fields_default_values.items(): + if k not in query_params_json: + query_params_json[k] = v + + if rest_numeric_enums: + query_params_json["$alt"] = "json;enum-encoding=int" + + return transcoded_request, body_json, query_params_json diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/gapic_metadata.json b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/gapic_metadata.json new file mode 100644 index 000000000000..86094e894b08 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/gapic_metadata.json @@ -0,0 +1,347 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.network_services_v1beta1", + "protoPackage": "google.cloud.networkservices.v1beta1", + "schema": "1.0", + "services": { + "DepService": { + "clients": { + "grpc": { + "libraryClient": "DepServiceClient", + "rpcs": { + "CreateExtensionBinding": { + "methods": [ + "create_extension_binding" + ] + }, + "CreateLbRouteExtension": { + "methods": [ + "create_lb_route_extension" + ] + }, + "CreateLbTrafficExtension": { + "methods": [ + "create_lb_traffic_extension" + ] + }, + "DeleteExtensionBinding": { + "methods": [ + "delete_extension_binding" + ] + }, + "DeleteLbRouteExtension": { + "methods": [ + "delete_lb_route_extension" + ] + }, + "DeleteLbTrafficExtension": { + "methods": [ + "delete_lb_traffic_extension" + ] + }, + "GetExtensionBinding": { + "methods": [ + "get_extension_binding" + ] + }, + "GetLbRouteExtension": { + "methods": [ + "get_lb_route_extension" + ] + }, + "GetLbTrafficExtension": { + "methods": [ + "get_lb_traffic_extension" + ] + }, + "ListExtensionBindings": { + "methods": [ + "list_extension_bindings" + ] + }, + "ListLbRouteExtensions": { + "methods": [ + "list_lb_route_extensions" + ] + }, + "ListLbTrafficExtensions": { + "methods": [ + "list_lb_traffic_extensions" + ] + }, + "UpdateExtensionBinding": { + "methods": [ + "update_extension_binding" + ] + }, + "UpdateLbRouteExtension": { + "methods": [ + "update_lb_route_extension" + ] + }, + "UpdateLbTrafficExtension": { + "methods": [ + "update_lb_traffic_extension" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DepServiceAsyncClient", + "rpcs": { + "CreateExtensionBinding": { + "methods": [ + "create_extension_binding" + ] + }, + "CreateLbRouteExtension": { + "methods": [ + "create_lb_route_extension" + ] + }, + "CreateLbTrafficExtension": { + "methods": [ + "create_lb_traffic_extension" + ] + }, + "DeleteExtensionBinding": { + "methods": [ + "delete_extension_binding" + ] + }, + "DeleteLbRouteExtension": { + "methods": [ + "delete_lb_route_extension" + ] + }, + "DeleteLbTrafficExtension": { + "methods": [ + "delete_lb_traffic_extension" + ] + }, + "GetExtensionBinding": { + "methods": [ + "get_extension_binding" + ] + }, + "GetLbRouteExtension": { + "methods": [ + "get_lb_route_extension" + ] + }, + "GetLbTrafficExtension": { + "methods": [ + "get_lb_traffic_extension" + ] + }, + "ListExtensionBindings": { + "methods": [ + "list_extension_bindings" + ] + }, + "ListLbRouteExtensions": { + "methods": [ + "list_lb_route_extensions" + ] + }, + "ListLbTrafficExtensions": { + "methods": [ + "list_lb_traffic_extensions" + ] + }, + "UpdateExtensionBinding": { + "methods": [ + "update_extension_binding" + ] + }, + "UpdateLbRouteExtension": { + "methods": [ + "update_lb_route_extension" + ] + }, + "UpdateLbTrafficExtension": { + "methods": [ + "update_lb_traffic_extension" + ] + } + } + }, + "rest": { + "libraryClient": "DepServiceClient", + "rpcs": { + "CreateExtensionBinding": { + "methods": [ + "create_extension_binding" + ] + }, + "CreateLbRouteExtension": { + "methods": [ + "create_lb_route_extension" + ] + }, + "CreateLbTrafficExtension": { + "methods": [ + "create_lb_traffic_extension" + ] + }, + "DeleteExtensionBinding": { + "methods": [ + "delete_extension_binding" + ] + }, + "DeleteLbRouteExtension": { + "methods": [ + "delete_lb_route_extension" + ] + }, + "DeleteLbTrafficExtension": { + "methods": [ + "delete_lb_traffic_extension" + ] + }, + "GetExtensionBinding": { + "methods": [ + "get_extension_binding" + ] + }, + "GetLbRouteExtension": { + "methods": [ + "get_lb_route_extension" + ] + }, + "GetLbTrafficExtension": { + "methods": [ + "get_lb_traffic_extension" + ] + }, + "ListExtensionBindings": { + "methods": [ + "list_extension_bindings" + ] + }, + "ListLbRouteExtensions": { + "methods": [ + "list_lb_route_extensions" + ] + }, + "ListLbTrafficExtensions": { + "methods": [ + "list_lb_traffic_extensions" + ] + }, + "UpdateExtensionBinding": { + "methods": [ + "update_extension_binding" + ] + }, + "UpdateLbRouteExtension": { + "methods": [ + "update_lb_route_extension" + ] + }, + "UpdateLbTrafficExtension": { + "methods": [ + "update_lb_traffic_extension" + ] + } + } + } + } + }, + "NetworkServices": { + "clients": { + "grpc": { + "libraryClient": "NetworkServicesClient", + "rpcs": { + "CreateEndpointPolicy": { + "methods": [ + "create_endpoint_policy" + ] + }, + "DeleteEndpointPolicy": { + "methods": [ + "delete_endpoint_policy" + ] + }, + "GetEndpointPolicy": { + "methods": [ + "get_endpoint_policy" + ] + }, + "ListEndpointPolicies": { + "methods": [ + "list_endpoint_policies" + ] + }, + "UpdateEndpointPolicy": { + "methods": [ + "update_endpoint_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NetworkServicesAsyncClient", + "rpcs": { + "CreateEndpointPolicy": { + "methods": [ + "create_endpoint_policy" + ] + }, + "DeleteEndpointPolicy": { + "methods": [ + "delete_endpoint_policy" + ] + }, + "GetEndpointPolicy": { + "methods": [ + "get_endpoint_policy" + ] + }, + "ListEndpointPolicies": { + "methods": [ + "list_endpoint_policies" + ] + }, + "UpdateEndpointPolicy": { + "methods": [ + "update_endpoint_policy" + ] + } + } + }, + "rest": { + "libraryClient": "NetworkServicesClient", + "rpcs": { + "CreateEndpointPolicy": { + "methods": [ + "create_endpoint_policy" + ] + }, + "DeleteEndpointPolicy": { + "methods": [ + "delete_endpoint_policy" + ] + }, + "GetEndpointPolicy": { + "methods": [ + "get_endpoint_policy" + ] + }, + "ListEndpointPolicies": { + "methods": [ + "list_endpoint_policies" + ] + }, + "UpdateEndpointPolicy": { + "methods": [ + "update_endpoint_policy" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/gapic_version.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/gapic_version.py new file mode 100644 index 000000000000..a37a7120a0ba --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/py.typed b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/py.typed new file mode 100644 index 000000000000..dfe9bf70b7d5 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-services package uses inline types. diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/__init__.py new file mode 100644 index 000000000000..f817433e7a8a --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import DepServiceAsyncClient +from .client import DepServiceClient + +__all__ = ( + "DepServiceClient", + "DepServiceAsyncClient", +) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/async_client.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/async_client.py new file mode 100644 index 000000000000..52cb67e023c7 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/async_client.py @@ -0,0 +1,3027 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_services_v1beta1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_services_v1beta1.services.dep_service import pagers +from google.cloud.network_services_v1beta1.types import common, dep + +from .client import DepServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, DepServiceTransport +from .transports.grpc_asyncio import DepServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class DepServiceAsyncClient: + """Service describing handlers for resources.""" + + _client: DepServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = DepServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DepServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = DepServiceClient._DEFAULT_UNIVERSE + + extension_binding_path = staticmethod(DepServiceClient.extension_binding_path) + parse_extension_binding_path = staticmethod( + DepServiceClient.parse_extension_binding_path + ) + lb_route_extension_path = staticmethod(DepServiceClient.lb_route_extension_path) + parse_lb_route_extension_path = staticmethod( + DepServiceClient.parse_lb_route_extension_path + ) + lb_traffic_extension_path = staticmethod(DepServiceClient.lb_traffic_extension_path) + parse_lb_traffic_extension_path = staticmethod( + DepServiceClient.parse_lb_traffic_extension_path + ) + common_billing_account_path = staticmethod( + DepServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + DepServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(DepServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DepServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DepServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + DepServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(DepServiceClient.common_project_path) + parse_common_project_path = staticmethod(DepServiceClient.parse_common_project_path) + common_location_path = staticmethod(DepServiceClient.common_location_path) + parse_common_location_path = staticmethod( + DepServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DepServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + DepServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(DepServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DepServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + DepServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(DepServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DepServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DepServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DepServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = DepServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, DepServiceTransport, Callable[..., DepServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dep service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,DepServiceTransport,Callable[..., DepServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DepServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DepServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networkservices_v1beta1.DepServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "credentialsType": None, + }, + ) + + async def list_lb_traffic_extensions( + self, + request: Optional[Union[dep.ListLbTrafficExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLbTrafficExtensionsAsyncPager: + r"""Lists ``LbTrafficExtension`` resources in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsRequest, dict]]): + The request object. Message for requesting list of ``LbTrafficExtension`` + resources. + parent (:class:`str`): + Required. The project and location from which the + ``LbTrafficExtension`` resources are listed, specified + in the following format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbTrafficExtensionsAsyncPager: + Message for response to listing LbTrafficExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.ListLbTrafficExtensionsRequest): + request = dep.ListLbTrafficExtensionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_lb_traffic_extensions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLbTrafficExtensionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_lb_traffic_extension( + self, + request: Optional[Union[dep.GetLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.LbTrafficExtension: + r"""Gets details of the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.GetLbTrafficExtensionRequest, dict]]): + The request object. Message for getting a ``LbTrafficExtension`` resource. + name (:class:`str`): + Required. A name of the ``LbTrafficExtension`` resource + to get. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.LbTrafficExtension: + LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.GetLbTrafficExtensionRequest): + request = dep.GetLbTrafficExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_lb_traffic_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_lb_traffic_extension( + self, + request: Optional[Union[dep.CreateLbTrafficExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + lb_traffic_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ``LbTrafficExtension`` resource in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = await client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.CreateLbTrafficExtensionRequest, dict]]): + The request object. Message for creating a ``LbTrafficExtension`` resource. + parent (:class:`str`): + Required. The parent resource of the + ``LbTrafficExtension`` resource. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_traffic_extension (:class:`google.cloud.network_services_v1beta1.types.LbTrafficExtension`): + Required. ``LbTrafficExtension`` resource to be created. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_traffic_extension_id (:class:`str`): + Required. User-provided ID of the ``LbTrafficExtension`` + resource to be created. + + This corresponds to the ``lb_traffic_extension_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, lb_traffic_extension, lb_traffic_extension_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.CreateLbTrafficExtensionRequest): + request = dep.CreateLbTrafficExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + if lb_traffic_extension_id is not None: + request.lb_traffic_extension_id = lb_traffic_extension_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_lb_traffic_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_lb_traffic_extension( + self, + request: Optional[Union[dep.UpdateLbTrafficExtensionRequest, dict]] = None, + *, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = await client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.UpdateLbTrafficExtensionRequest, dict]]): + The request object. Message for updating a ``LbTrafficExtension`` resource. + lb_traffic_extension (:class:`google.cloud.network_services_v1beta1.types.LbTrafficExtension`): + Required. ``LbTrafficExtension`` resource being updated. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Used to specify the fields to be overwritten + in the ``LbTrafficExtension`` resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field is + overwritten if it is in the mask. If the user does not + specify a mask, then all fields are overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [lb_traffic_extension, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.UpdateLbTrafficExtensionRequest): + request = dep.UpdateLbTrafficExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_lb_traffic_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("lb_traffic_extension.name", request.lb_traffic_extension.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_lb_traffic_extension( + self, + request: Optional[Union[dep.DeleteLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.DeleteLbTrafficExtensionRequest, dict]]): + The request object. Message for deleting a ``LbTrafficExtension`` resource. + name (:class:`str`): + Required. The name of the ``LbTrafficExtension`` + resource to delete. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.DeleteLbTrafficExtensionRequest): + request = dep.DeleteLbTrafficExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_lb_traffic_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_lb_route_extensions( + self, + request: Optional[Union[dep.ListLbRouteExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLbRouteExtensionsAsyncPager: + r"""Lists ``LbRouteExtension`` resources in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsRequest, dict]]): + The request object. Message for requesting list of ``LbRouteExtension`` + resources. + parent (:class:`str`): + Required. The project and location from which the + ``LbRouteExtension`` resources are listed, specified in + the following format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbRouteExtensionsAsyncPager: + Message for response to listing LbRouteExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.ListLbRouteExtensionsRequest): + request = dep.ListLbRouteExtensionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_lb_route_extensions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListLbRouteExtensionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_lb_route_extension( + self, + request: Optional[Union[dep.GetLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.LbRouteExtension: + r"""Gets details of the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.GetLbRouteExtensionRequest, dict]]): + The request object. Message for getting a ``LbRouteExtension`` resource. + name (:class:`str`): + Required. A name of the ``LbRouteExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.LbRouteExtension: + LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.GetLbRouteExtensionRequest): + request = dep.GetLbRouteExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_lb_route_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_lb_route_extension( + self, + request: Optional[Union[dep.CreateLbRouteExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + lb_route_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ``LbRouteExtension`` resource in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = await client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.CreateLbRouteExtensionRequest, dict]]): + The request object. Message for creating a ``LbRouteExtension`` resource. + parent (:class:`str`): + Required. The parent resource of the + ``LbRouteExtension`` resource. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_route_extension (:class:`google.cloud.network_services_v1beta1.types.LbRouteExtension`): + Required. ``LbRouteExtension`` resource to be created. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_route_extension_id (:class:`str`): + Required. User-provided ID of the ``LbRouteExtension`` + resource to be created. + + This corresponds to the ``lb_route_extension_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, lb_route_extension, lb_route_extension_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.CreateLbRouteExtensionRequest): + request = dep.CreateLbRouteExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + if lb_route_extension_id is not None: + request.lb_route_extension_id = lb_route_extension_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_lb_route_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_lb_route_extension( + self, + request: Optional[Union[dep.UpdateLbRouteExtensionRequest, dict]] = None, + *, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of the specified ``LbRouteExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = await client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.UpdateLbRouteExtensionRequest, dict]]): + The request object. Message for updating a ``LbRouteExtension`` resource. + lb_route_extension (:class:`google.cloud.network_services_v1beta1.types.LbRouteExtension`): + Required. ``LbRouteExtension`` resource being updated. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Used to specify the fields to be overwritten + in the ``LbRouteExtension`` resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field is overwritten + if it is in the mask. If the user does not specify a + mask, then all fields are overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [lb_route_extension, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.UpdateLbRouteExtensionRequest): + request = dep.UpdateLbRouteExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_lb_route_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("lb_route_extension.name", request.lb_route_extension.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_lb_route_extension( + self, + request: Optional[Union[dep.DeleteLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.DeleteLbRouteExtensionRequest, dict]]): + The request object. Message for deleting a ``LbRouteExtension`` resource. + name (:class:`str`): + Required. The name of the ``LbRouteExtension`` resource + to delete. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.DeleteLbRouteExtensionRequest): + request = dep.DeleteLbRouteExtensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_lb_route_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_extension_bindings( + self, + request: Optional[Union[dep.ListExtensionBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExtensionBindingsAsyncPager: + r"""Lists ``ExtensionBinding`` resources in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_list_extension_bindings(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListExtensionBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_extension_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.ListExtensionBindingsRequest, dict]]): + The request object. Request used with the ``ListExtensionBindings`` method. + parent (:class:`str`): + Required. The project and location from which the + ``ExtensionBinding`` resources should be listed, + specified in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.dep_service.pagers.ListExtensionBindingsAsyncPager: + Response returned by the ListExtensionBindings method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.ListExtensionBindingsRequest): + request = dep.ListExtensionBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_extension_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListExtensionBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_extension_binding( + self, + request: Optional[Union[dep.GetExtensionBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.ExtensionBinding: + r"""Gets details of the specified ``ExtensionBinding`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_get_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetExtensionBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_extension_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.GetExtensionBindingRequest, dict]]): + The request object. Request used by the ``GetExtensionBinding`` method. + name (:class:`str`): + Required. A name of the ``ExtensionBinding`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.ExtensionBinding: + ExtensionBinding is a resource representing the attachment of an extension + to a service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.GetExtensionBindingRequest): + request = dep.GetExtensionBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_extension_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_extension_binding( + self, + request: Optional[Union[dep.CreateExtensionBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + extension_binding: Optional[dep.ExtensionBinding] = None, + extension_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ``ExtensionBinding`` resource in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_create_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.CreateExtensionBindingRequest( + parent="parent_value", + extension_binding_id="extension_binding_id_value", + extension_binding=extension_binding, + ) + + # Make the request + operation = await client.create_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.CreateExtensionBindingRequest, dict]]): + The request object. Request used by the ``CreateExtensionBinding`` method. + parent (:class:`str`): + Required. The parent resource of the + ``ExtensionBinding`` resource. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + extension_binding (:class:`google.cloud.network_services_v1beta1.types.ExtensionBinding`): + Required. ``ExtensionBinding`` resource to be created. + This corresponds to the ``extension_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + extension_binding_id (:class:`str`): + Required. Short name of the ``ExtensionBinding`` + resource to be created. + + This corresponds to the ``extension_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.ExtensionBinding` ExtensionBinding is a resource representing the attachment of an extension + to a service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, extension_binding, extension_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.CreateExtensionBindingRequest): + request = dep.CreateExtensionBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if extension_binding is not None: + request.extension_binding = extension_binding + if extension_binding_id is not None: + request.extension_binding_id = extension_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_extension_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dep.ExtensionBinding, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_extension_binding( + self, + request: Optional[Union[dep.UpdateExtensionBindingRequest, dict]] = None, + *, + extension_binding: Optional[dep.ExtensionBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of the specified ``ExtensionBinding`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_update_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.UpdateExtensionBindingRequest( + extension_binding=extension_binding, + ) + + # Make the request + operation = await client.update_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.UpdateExtensionBindingRequest, dict]]): + The request object. Request used by the ``UpdateExtensionBinding`` method. + extension_binding (:class:`google.cloud.network_services_v1beta1.types.ExtensionBinding`): + Required. Updated ``ExtensionBinding`` resource. + This corresponds to the ``extension_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the ``ExtensionBinding`` resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.ExtensionBinding` ExtensionBinding is a resource representing the attachment of an extension + to a service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [extension_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.UpdateExtensionBindingRequest): + request = dep.UpdateExtensionBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if extension_binding is not None: + request.extension_binding = extension_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_extension_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("extension_binding.name", request.extension_binding.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dep.ExtensionBinding, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_extension_binding( + self, + request: Optional[Union[dep.DeleteExtensionBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified ``ExtensionBinding`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_delete_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteExtensionBindingRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.DeleteExtensionBindingRequest, dict]]): + The request object. Request used by the ``DeleteExtensionBinding`` method. + name (:class:`str`): + Required. A name of the ``ExtensionBinding`` resource to + delete. Must be in the format + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.DeleteExtensionBindingRequest): + request = dep.DeleteExtensionBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_extension_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DepServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("DepServiceAsyncClient",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/client.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/client.py new file mode 100644 index 000000000000..e859b4b4e399 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/client.py @@ -0,0 +1,3365 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_services_v1beta1 import gapic_version as package_version +from google.cloud.network_services_v1beta1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_services_v1beta1.services.dep_service import pagers +from google.cloud.network_services_v1beta1.types import common, dep + +from .transports.base import DEFAULT_CLIENT_INFO, DepServiceTransport +from .transports.grpc import DepServiceGrpcTransport +from .transports.grpc_asyncio import DepServiceGrpcAsyncIOTransport +from .transports.rest import DepServiceRestTransport + + +class DepServiceClientMeta(type): + """Metaclass for the DepService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[DepServiceTransport]] + _transport_registry["grpc"] = DepServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DepServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DepServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[DepServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DepServiceClient(metaclass=DepServiceClientMeta): + """Service describing handlers for resources.""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "networkservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "networkservices.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DepServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DepServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DepServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DepServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def extension_binding_path( + project: str, + location: str, + extension_binding: str, + ) -> str: + """Returns a fully-qualified extension_binding string.""" + return "projects/{project}/locations/{location}/extensionBindings/{extension_binding}".format( + project=project, + location=location, + extension_binding=extension_binding, + ) + + @staticmethod + def parse_extension_binding_path(path: str) -> Dict[str, str]: + """Parses a extension_binding path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/extensionBindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def lb_route_extension_path( + project: str, + location: str, + lb_route_extension: str, + ) -> str: + """Returns a fully-qualified lb_route_extension string.""" + return "projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}".format( + project=project, + location=location, + lb_route_extension=lb_route_extension, + ) + + @staticmethod + def parse_lb_route_extension_path(path: str) -> Dict[str, str]: + """Parses a lb_route_extension path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/lbRouteExtensions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def lb_traffic_extension_path( + project: str, + location: str, + lb_traffic_extension: str, + ) -> str: + """Returns a fully-qualified lb_traffic_extension string.""" + return "projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}".format( + project=project, + location=location, + lb_traffic_extension=lb_traffic_extension, + ) + + @staticmethod + def parse_lb_traffic_extension_path(path: str) -> Dict[str, str]: + """Parses a lb_traffic_extension path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/lbTrafficExtensions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, DepServiceTransport, Callable[..., DepServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the dep service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,DepServiceTransport,Callable[..., DepServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DepServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = DepServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=DepServiceClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, DepServiceTransport) + if transport_provided: + # transport is a DepServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(DepServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=DepServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=DepServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[DepServiceTransport], Callable[..., DepServiceTransport] + ] = ( + DepServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DepServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networkservices_v1beta1.DepServiceClient`.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "credentialsType": None, + }, + ) + + def list_lb_traffic_extensions( + self, + request: Optional[Union[dep.ListLbTrafficExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLbTrafficExtensionsPager: + r"""Lists ``LbTrafficExtension`` resources in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsRequest, dict]): + The request object. Message for requesting list of ``LbTrafficExtension`` + resources. + parent (str): + Required. The project and location from which the + ``LbTrafficExtension`` resources are listed, specified + in the following format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbTrafficExtensionsPager: + Message for response to listing LbTrafficExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.ListLbTrafficExtensionsRequest): + request = dep.ListLbTrafficExtensionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_lb_traffic_extensions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLbTrafficExtensionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_lb_traffic_extension( + self, + request: Optional[Union[dep.GetLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.LbTrafficExtension: + r"""Gets details of the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.GetLbTrafficExtensionRequest, dict]): + The request object. Message for getting a ``LbTrafficExtension`` resource. + name (str): + Required. A name of the ``LbTrafficExtension`` resource + to get. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.LbTrafficExtension: + LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.GetLbTrafficExtensionRequest): + request = dep.GetLbTrafficExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_lb_traffic_extension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_lb_traffic_extension( + self, + request: Optional[Union[dep.CreateLbTrafficExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + lb_traffic_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ``LbTrafficExtension`` resource in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.CreateLbTrafficExtensionRequest, dict]): + The request object. Message for creating a ``LbTrafficExtension`` resource. + parent (str): + Required. The parent resource of the + ``LbTrafficExtension`` resource. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_traffic_extension (google.cloud.network_services_v1beta1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` resource to be created. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_traffic_extension_id (str): + Required. User-provided ID of the ``LbTrafficExtension`` + resource to be created. + + This corresponds to the ``lb_traffic_extension_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, lb_traffic_extension, lb_traffic_extension_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.CreateLbTrafficExtensionRequest): + request = dep.CreateLbTrafficExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + if lb_traffic_extension_id is not None: + request.lb_traffic_extension_id = lb_traffic_extension_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_lb_traffic_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_lb_traffic_extension( + self, + request: Optional[Union[dep.UpdateLbTrafficExtensionRequest, dict]] = None, + *, + lb_traffic_extension: Optional[dep.LbTrafficExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.UpdateLbTrafficExtensionRequest, dict]): + The request object. Message for updating a ``LbTrafficExtension`` resource. + lb_traffic_extension (google.cloud.network_services_v1beta1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` resource being updated. + This corresponds to the ``lb_traffic_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Used to specify the fields to be overwritten + in the ``LbTrafficExtension`` resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field is + overwritten if it is in the mask. If the user does not + specify a mask, then all fields are overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbTrafficExtension` LbTrafficExtension is a resource that lets the extension service modify the + headers and payloads of both requests and responses + without impacting the choice of backend services or + any other security policies associated with the + backend service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [lb_traffic_extension, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.UpdateLbTrafficExtensionRequest): + request = dep.UpdateLbTrafficExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_traffic_extension is not None: + request.lb_traffic_extension = lb_traffic_extension + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_lb_traffic_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("lb_traffic_extension.name", request.lb_traffic_extension.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dep.LbTrafficExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_lb_traffic_extension( + self, + request: Optional[Union[dep.DeleteLbTrafficExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the specified ``LbTrafficExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.DeleteLbTrafficExtensionRequest, dict]): + The request object. Message for deleting a ``LbTrafficExtension`` resource. + name (str): + Required. The name of the ``LbTrafficExtension`` + resource to delete. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.DeleteLbTrafficExtensionRequest): + request = dep.DeleteLbTrafficExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_lb_traffic_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_lb_route_extensions( + self, + request: Optional[Union[dep.ListLbRouteExtensionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLbRouteExtensionsPager: + r"""Lists ``LbRouteExtension`` resources in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsRequest, dict]): + The request object. Message for requesting list of ``LbRouteExtension`` + resources. + parent (str): + Required. The project and location from which the + ``LbRouteExtension`` resources are listed, specified in + the following format: + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbRouteExtensionsPager: + Message for response to listing LbRouteExtension + resources. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.ListLbRouteExtensionsRequest): + request = dep.ListLbRouteExtensionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_lb_route_extensions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListLbRouteExtensionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_lb_route_extension( + self, + request: Optional[Union[dep.GetLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.LbRouteExtension: + r"""Gets details of the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.GetLbRouteExtensionRequest, dict]): + The request object. Message for getting a ``LbRouteExtension`` resource. + name (str): + Required. A name of the ``LbRouteExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.LbRouteExtension: + LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.GetLbRouteExtensionRequest): + request = dep.GetLbRouteExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_lb_route_extension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_lb_route_extension( + self, + request: Optional[Union[dep.CreateLbRouteExtensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + lb_route_extension_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ``LbRouteExtension`` resource in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.CreateLbRouteExtensionRequest, dict]): + The request object. Message for creating a ``LbRouteExtension`` resource. + parent (str): + Required. The parent resource of the + ``LbRouteExtension`` resource. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_route_extension (google.cloud.network_services_v1beta1.types.LbRouteExtension): + Required. ``LbRouteExtension`` resource to be created. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lb_route_extension_id (str): + Required. User-provided ID of the ``LbRouteExtension`` + resource to be created. + + This corresponds to the ``lb_route_extension_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, lb_route_extension, lb_route_extension_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.CreateLbRouteExtensionRequest): + request = dep.CreateLbRouteExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + if lb_route_extension_id is not None: + request.lb_route_extension_id = lb_route_extension_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_lb_route_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_lb_route_extension( + self, + request: Optional[Union[dep.UpdateLbRouteExtensionRequest, dict]] = None, + *, + lb_route_extension: Optional[dep.LbRouteExtension] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of the specified ``LbRouteExtension`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = ['forwarding_rules_value1', 'forwarding_rules_value2'] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = "cel_expression_value" + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.UpdateLbRouteExtensionRequest, dict]): + The request object. Message for updating a ``LbRouteExtension`` resource. + lb_route_extension (google.cloud.network_services_v1beta1.types.LbRouteExtension): + Required. ``LbRouteExtension`` resource being updated. + This corresponds to the ``lb_route_extension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Used to specify the fields to be overwritten + in the ``LbRouteExtension`` resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field is overwritten + if it is in the mask. If the user does not specify a + mask, then all fields are overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.LbRouteExtension` LbRouteExtension is a resource that lets you control where traffic is + routed to for a given request. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [lb_route_extension, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.UpdateLbRouteExtensionRequest): + request = dep.UpdateLbRouteExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if lb_route_extension is not None: + request.lb_route_extension = lb_route_extension + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_lb_route_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("lb_route_extension.name", request.lb_route_extension.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dep.LbRouteExtension, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_lb_route_extension( + self, + request: Optional[Union[dep.DeleteLbRouteExtensionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the specified ``LbRouteExtension`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.DeleteLbRouteExtensionRequest, dict]): + The request object. Message for deleting a ``LbRouteExtension`` resource. + name (str): + Required. The name of the ``LbRouteExtension`` resource + to delete. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.DeleteLbRouteExtensionRequest): + request = dep.DeleteLbRouteExtensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_lb_route_extension + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_extension_bindings( + self, + request: Optional[Union[dep.ListExtensionBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExtensionBindingsPager: + r"""Lists ``ExtensionBinding`` resources in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_list_extension_bindings(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListExtensionBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_extension_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.ListExtensionBindingsRequest, dict]): + The request object. Request used with the ``ListExtensionBindings`` method. + parent (str): + Required. The project and location from which the + ``ExtensionBinding`` resources should be listed, + specified in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.dep_service.pagers.ListExtensionBindingsPager: + Response returned by the ListExtensionBindings method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.ListExtensionBindingsRequest): + request = dep.ListExtensionBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_extension_bindings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListExtensionBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_extension_binding( + self, + request: Optional[Union[dep.GetExtensionBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.ExtensionBinding: + r"""Gets details of the specified ``ExtensionBinding`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_get_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetExtensionBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_extension_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.GetExtensionBindingRequest, dict]): + The request object. Request used by the ``GetExtensionBinding`` method. + name (str): + Required. A name of the ``ExtensionBinding`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.ExtensionBinding: + ExtensionBinding is a resource representing the attachment of an extension + to a service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.GetExtensionBindingRequest): + request = dep.GetExtensionBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_extension_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_extension_binding( + self, + request: Optional[Union[dep.CreateExtensionBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + extension_binding: Optional[dep.ExtensionBinding] = None, + extension_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ``ExtensionBinding`` resource in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_create_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.CreateExtensionBindingRequest( + parent="parent_value", + extension_binding_id="extension_binding_id_value", + extension_binding=extension_binding, + ) + + # Make the request + operation = client.create_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.CreateExtensionBindingRequest, dict]): + The request object. Request used by the ``CreateExtensionBinding`` method. + parent (str): + Required. The parent resource of the + ``ExtensionBinding`` resource. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + extension_binding (google.cloud.network_services_v1beta1.types.ExtensionBinding): + Required. ``ExtensionBinding`` resource to be created. + This corresponds to the ``extension_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + extension_binding_id (str): + Required. Short name of the ``ExtensionBinding`` + resource to be created. + + This corresponds to the ``extension_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.ExtensionBinding` ExtensionBinding is a resource representing the attachment of an extension + to a service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, extension_binding, extension_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.CreateExtensionBindingRequest): + request = dep.CreateExtensionBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if extension_binding is not None: + request.extension_binding = extension_binding + if extension_binding_id is not None: + request.extension_binding_id = extension_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_extension_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dep.ExtensionBinding, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_extension_binding( + self, + request: Optional[Union[dep.UpdateExtensionBindingRequest, dict]] = None, + *, + extension_binding: Optional[dep.ExtensionBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of the specified ``ExtensionBinding`` + resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_update_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.UpdateExtensionBindingRequest( + extension_binding=extension_binding, + ) + + # Make the request + operation = client.update_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.UpdateExtensionBindingRequest, dict]): + The request object. Request used by the ``UpdateExtensionBinding`` method. + extension_binding (google.cloud.network_services_v1beta1.types.ExtensionBinding): + Required. Updated ``ExtensionBinding`` resource. + This corresponds to the ``extension_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ``ExtensionBinding`` resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.ExtensionBinding` ExtensionBinding is a resource representing the attachment of an extension + to a service. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [extension_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.UpdateExtensionBindingRequest): + request = dep.UpdateExtensionBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if extension_binding is not None: + request.extension_binding = extension_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_extension_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("extension_binding.name", request.extension_binding.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dep.ExtensionBinding, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_extension_binding( + self, + request: Optional[Union[dep.DeleteExtensionBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the specified ``ExtensionBinding`` resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_delete_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteExtensionBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.DeleteExtensionBindingRequest, dict]): + The request object. Request used by the ``DeleteExtensionBinding`` method. + name (str): + Required. A name of the ``ExtensionBinding`` resource to + delete. Must be in the format + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, dep.DeleteExtensionBindingRequest): + request = dep.DeleteExtensionBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_extension_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DepServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("DepServiceClient",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/pagers.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/pagers.py new file mode 100644 index 000000000000..95138f794f40 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/pagers.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.network_services_v1beta1.types import dep + + +class ListLbTrafficExtensionsPager: + """A pager for iterating through ``list_lb_traffic_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``lb_traffic_extensions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLbTrafficExtensions`` requests and continue to iterate + through the ``lb_traffic_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., dep.ListLbTrafficExtensionsResponse], + request: dep.ListLbTrafficExtensionsRequest, + response: dep.ListLbTrafficExtensionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = dep.ListLbTrafficExtensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[dep.ListLbTrafficExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[dep.LbTrafficExtension]: + for page in self.pages: + yield from page.lb_traffic_extensions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLbTrafficExtensionsAsyncPager: + """A pager for iterating through ``list_lb_traffic_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``lb_traffic_extensions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLbTrafficExtensions`` requests and continue to iterate + through the ``lb_traffic_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[dep.ListLbTrafficExtensionsResponse]], + request: dep.ListLbTrafficExtensionsRequest, + response: dep.ListLbTrafficExtensionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = dep.ListLbTrafficExtensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[dep.ListLbTrafficExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[dep.LbTrafficExtension]: + async def async_generator(): + async for page in self.pages: + for response in page.lb_traffic_extensions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLbRouteExtensionsPager: + """A pager for iterating through ``list_lb_route_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``lb_route_extensions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListLbRouteExtensions`` requests and continue to iterate + through the ``lb_route_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., dep.ListLbRouteExtensionsResponse], + request: dep.ListLbRouteExtensionsRequest, + response: dep.ListLbRouteExtensionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = dep.ListLbRouteExtensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[dep.ListLbRouteExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[dep.LbRouteExtension]: + for page in self.pages: + yield from page.lb_route_extensions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListLbRouteExtensionsAsyncPager: + """A pager for iterating through ``list_lb_route_extensions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``lb_route_extensions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListLbRouteExtensions`` requests and continue to iterate + through the ``lb_route_extensions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[dep.ListLbRouteExtensionsResponse]], + request: dep.ListLbRouteExtensionsRequest, + response: dep.ListLbRouteExtensionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = dep.ListLbRouteExtensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[dep.ListLbRouteExtensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[dep.LbRouteExtension]: + async def async_generator(): + async for page in self.pages: + for response in page.lb_route_extensions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExtensionBindingsPager: + """A pager for iterating through ``list_extension_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListExtensionBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``extension_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExtensionBindings`` requests and continue to iterate + through the ``extension_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListExtensionBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., dep.ListExtensionBindingsResponse], + request: dep.ListExtensionBindingsRequest, + response: dep.ListExtensionBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListExtensionBindingsRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListExtensionBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = dep.ListExtensionBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[dep.ListExtensionBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[dep.ExtensionBinding]: + for page in self.pages: + yield from page.extension_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExtensionBindingsAsyncPager: + """A pager for iterating through ``list_extension_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListExtensionBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``extension_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExtensionBindings`` requests and continue to iterate + through the ``extension_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListExtensionBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[dep.ListExtensionBindingsResponse]], + request: dep.ListExtensionBindingsRequest, + response: dep.ListExtensionBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListExtensionBindingsRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListExtensionBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = dep.ListExtensionBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[dep.ListExtensionBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[dep.ExtensionBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.extension_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/README.rst b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/README.rst new file mode 100644 index 000000000000..2f98eba32050 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``DepServiceTransport`` is the ABC for all transports. + +- public child ``DepServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``DepServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseDepServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``DepServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/__init__.py new file mode 100644 index 000000000000..0602340f8dc5 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DepServiceTransport +from .grpc import DepServiceGrpcTransport +from .grpc_asyncio import DepServiceGrpcAsyncIOTransport +from .rest import DepServiceRestInterceptor, DepServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DepServiceTransport]] +_transport_registry["grpc"] = DepServiceGrpcTransport +_transport_registry["grpc_asyncio"] = DepServiceGrpcAsyncIOTransport +_transport_registry["rest"] = DepServiceRestTransport + +__all__ = ( + "DepServiceTransport", + "DepServiceGrpcTransport", + "DepServiceGrpcAsyncIOTransport", + "DepServiceRestTransport", + "DepServiceRestInterceptor", +) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/base.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/base.py new file mode 100644 index 000000000000..4cad07451660 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/base.py @@ -0,0 +1,524 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_services_v1beta1 import gapic_version as package_version +from google.cloud.network_services_v1beta1.types import dep + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DepServiceTransport(abc.ABC): + """Abstract transport class for DepService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "networkservices.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_lb_traffic_extensions: gapic_v1.method.wrap_method( + self.list_lb_traffic_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_traffic_extension: gapic_v1.method.wrap_method( + self.get_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_traffic_extension: gapic_v1.method.wrap_method( + self.create_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_traffic_extension: gapic_v1.method.wrap_method( + self.update_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_traffic_extension: gapic_v1.method.wrap_method( + self.delete_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.list_lb_route_extensions: gapic_v1.method.wrap_method( + self.list_lb_route_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_route_extension: gapic_v1.method.wrap_method( + self.get_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_route_extension: gapic_v1.method.wrap_method( + self.create_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_route_extension: gapic_v1.method.wrap_method( + self.update_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_route_extension: gapic_v1.method.wrap_method( + self.delete_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.list_extension_bindings: gapic_v1.method.wrap_method( + self.list_extension_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_extension_binding: gapic_v1.method.wrap_method( + self.get_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_extension_binding: gapic_v1.method.wrap_method( + self.create_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_extension_binding: gapic_v1.method.wrap_method( + self.update_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_extension_binding: gapic_v1.method.wrap_method( + self.delete_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_lb_traffic_extensions( + self, + ) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], + Union[ + dep.ListLbTrafficExtensionsResponse, + Awaitable[dep.ListLbTrafficExtensionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_lb_traffic_extension( + self, + ) -> Callable[ + [dep.GetLbTrafficExtensionRequest], + Union[dep.LbTrafficExtension, Awaitable[dep.LbTrafficExtension]], + ]: + raise NotImplementedError() + + @property + def create_lb_traffic_extension( + self, + ) -> Callable[ + [dep.CreateLbTrafficExtensionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_lb_traffic_extension( + self, + ) -> Callable[ + [dep.UpdateLbTrafficExtensionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_lb_traffic_extension( + self, + ) -> Callable[ + [dep.DeleteLbTrafficExtensionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_lb_route_extensions( + self, + ) -> Callable[ + [dep.ListLbRouteExtensionsRequest], + Union[ + dep.ListLbRouteExtensionsResponse, + Awaitable[dep.ListLbRouteExtensionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_lb_route_extension( + self, + ) -> Callable[ + [dep.GetLbRouteExtensionRequest], + Union[dep.LbRouteExtension, Awaitable[dep.LbRouteExtension]], + ]: + raise NotImplementedError() + + @property + def create_lb_route_extension( + self, + ) -> Callable[ + [dep.CreateLbRouteExtensionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_lb_route_extension( + self, + ) -> Callable[ + [dep.UpdateLbRouteExtensionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_lb_route_extension( + self, + ) -> Callable[ + [dep.DeleteLbRouteExtensionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_extension_bindings( + self, + ) -> Callable[ + [dep.ListExtensionBindingsRequest], + Union[ + dep.ListExtensionBindingsResponse, + Awaitable[dep.ListExtensionBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_extension_binding( + self, + ) -> Callable[ + [dep.GetExtensionBindingRequest], + Union[dep.ExtensionBinding, Awaitable[dep.ExtensionBinding]], + ]: + raise NotImplementedError() + + @property + def create_extension_binding( + self, + ) -> Callable[ + [dep.CreateExtensionBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_extension_binding( + self, + ) -> Callable[ + [dep.UpdateExtensionBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_extension_binding( + self, + ) -> Callable[ + [dep.DeleteExtensionBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("DepServiceTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/grpc.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/grpc.py new file mode 100644 index 000000000000..f47e620a0624 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/grpc.py @@ -0,0 +1,958 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.network_services_v1beta1.types import dep + +from .base import DEFAULT_CLIENT_INFO, DepServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DepServiceGrpcTransport(DepServiceTransport): + """gRPC backend transport for DepService. + + Service describing handlers for resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_lb_traffic_extensions( + self, + ) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], dep.ListLbTrafficExtensionsResponse + ]: + r"""Return a callable for the list lb traffic extensions method over gRPC. + + Lists ``LbTrafficExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbTrafficExtensionsRequest], + ~.ListLbTrafficExtensionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_lb_traffic_extensions" not in self._stubs: + self._stubs["list_lb_traffic_extensions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/ListLbTrafficExtensions", + request_serializer=dep.ListLbTrafficExtensionsRequest.serialize, + response_deserializer=dep.ListLbTrafficExtensionsResponse.deserialize, + ) + ) + return self._stubs["list_lb_traffic_extensions"] + + @property + def get_lb_traffic_extension( + self, + ) -> Callable[[dep.GetLbTrafficExtensionRequest], dep.LbTrafficExtension]: + r"""Return a callable for the get lb traffic extension method over gRPC. + + Gets details of the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.GetLbTrafficExtensionRequest], + ~.LbTrafficExtension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_lb_traffic_extension" not in self._stubs: + self._stubs["get_lb_traffic_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/GetLbTrafficExtension", + request_serializer=dep.GetLbTrafficExtensionRequest.serialize, + response_deserializer=dep.LbTrafficExtension.deserialize, + ) + return self._stubs["get_lb_traffic_extension"] + + @property + def create_lb_traffic_extension( + self, + ) -> Callable[[dep.CreateLbTrafficExtensionRequest], operations_pb2.Operation]: + r"""Return a callable for the create lb traffic extension method over gRPC. + + Creates a new ``LbTrafficExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbTrafficExtensionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_lb_traffic_extension" not in self._stubs: + self._stubs["create_lb_traffic_extension"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/CreateLbTrafficExtension", + request_serializer=dep.CreateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_lb_traffic_extension"] + + @property + def update_lb_traffic_extension( + self, + ) -> Callable[[dep.UpdateLbTrafficExtensionRequest], operations_pb2.Operation]: + r"""Return a callable for the update lb traffic extension method over gRPC. + + Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + Returns: + Callable[[~.UpdateLbTrafficExtensionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_lb_traffic_extension" not in self._stubs: + self._stubs["update_lb_traffic_extension"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/UpdateLbTrafficExtension", + request_serializer=dep.UpdateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_lb_traffic_extension"] + + @property + def delete_lb_traffic_extension( + self, + ) -> Callable[[dep.DeleteLbTrafficExtensionRequest], operations_pb2.Operation]: + r"""Return a callable for the delete lb traffic extension method over gRPC. + + Deletes the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.DeleteLbTrafficExtensionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_lb_traffic_extension" not in self._stubs: + self._stubs["delete_lb_traffic_extension"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/DeleteLbTrafficExtension", + request_serializer=dep.DeleteLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_lb_traffic_extension"] + + @property + def list_lb_route_extensions( + self, + ) -> Callable[ + [dep.ListLbRouteExtensionsRequest], dep.ListLbRouteExtensionsResponse + ]: + r"""Return a callable for the list lb route extensions method over gRPC. + + Lists ``LbRouteExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbRouteExtensionsRequest], + ~.ListLbRouteExtensionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_lb_route_extensions" not in self._stubs: + self._stubs["list_lb_route_extensions"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/ListLbRouteExtensions", + request_serializer=dep.ListLbRouteExtensionsRequest.serialize, + response_deserializer=dep.ListLbRouteExtensionsResponse.deserialize, + ) + return self._stubs["list_lb_route_extensions"] + + @property + def get_lb_route_extension( + self, + ) -> Callable[[dep.GetLbRouteExtensionRequest], dep.LbRouteExtension]: + r"""Return a callable for the get lb route extension method over gRPC. + + Gets details of the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.GetLbRouteExtensionRequest], + ~.LbRouteExtension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_lb_route_extension" not in self._stubs: + self._stubs["get_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/GetLbRouteExtension", + request_serializer=dep.GetLbRouteExtensionRequest.serialize, + response_deserializer=dep.LbRouteExtension.deserialize, + ) + return self._stubs["get_lb_route_extension"] + + @property + def create_lb_route_extension( + self, + ) -> Callable[[dep.CreateLbRouteExtensionRequest], operations_pb2.Operation]: + r"""Return a callable for the create lb route extension method over gRPC. + + Creates a new ``LbRouteExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbRouteExtensionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_lb_route_extension" not in self._stubs: + self._stubs["create_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/CreateLbRouteExtension", + request_serializer=dep.CreateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_lb_route_extension"] + + @property + def update_lb_route_extension( + self, + ) -> Callable[[dep.UpdateLbRouteExtensionRequest], operations_pb2.Operation]: + r"""Return a callable for the update lb route extension method over gRPC. + + Updates the parameters of the specified ``LbRouteExtension`` + resource. + + Returns: + Callable[[~.UpdateLbRouteExtensionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_lb_route_extension" not in self._stubs: + self._stubs["update_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/UpdateLbRouteExtension", + request_serializer=dep.UpdateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_lb_route_extension"] + + @property + def delete_lb_route_extension( + self, + ) -> Callable[[dep.DeleteLbRouteExtensionRequest], operations_pb2.Operation]: + r"""Return a callable for the delete lb route extension method over gRPC. + + Deletes the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.DeleteLbRouteExtensionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_lb_route_extension" not in self._stubs: + self._stubs["delete_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/DeleteLbRouteExtension", + request_serializer=dep.DeleteLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_lb_route_extension"] + + @property + def list_extension_bindings( + self, + ) -> Callable[ + [dep.ListExtensionBindingsRequest], dep.ListExtensionBindingsResponse + ]: + r"""Return a callable for the list extension bindings method over gRPC. + + Lists ``ExtensionBinding`` resources in a given project and + location. + + Returns: + Callable[[~.ListExtensionBindingsRequest], + ~.ListExtensionBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_extension_bindings" not in self._stubs: + self._stubs["list_extension_bindings"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/ListExtensionBindings", + request_serializer=dep.ListExtensionBindingsRequest.serialize, + response_deserializer=dep.ListExtensionBindingsResponse.deserialize, + ) + return self._stubs["list_extension_bindings"] + + @property + def get_extension_binding( + self, + ) -> Callable[[dep.GetExtensionBindingRequest], dep.ExtensionBinding]: + r"""Return a callable for the get extension binding method over gRPC. + + Gets details of the specified ``ExtensionBinding`` resource. + + Returns: + Callable[[~.GetExtensionBindingRequest], + ~.ExtensionBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_extension_binding" not in self._stubs: + self._stubs["get_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/GetExtensionBinding", + request_serializer=dep.GetExtensionBindingRequest.serialize, + response_deserializer=dep.ExtensionBinding.deserialize, + ) + return self._stubs["get_extension_binding"] + + @property + def create_extension_binding( + self, + ) -> Callable[[dep.CreateExtensionBindingRequest], operations_pb2.Operation]: + r"""Return a callable for the create extension binding method over gRPC. + + Creates a new ``ExtensionBinding`` resource in a given project + and location. + + Returns: + Callable[[~.CreateExtensionBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_extension_binding" not in self._stubs: + self._stubs["create_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/CreateExtensionBinding", + request_serializer=dep.CreateExtensionBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_extension_binding"] + + @property + def update_extension_binding( + self, + ) -> Callable[[dep.UpdateExtensionBindingRequest], operations_pb2.Operation]: + r"""Return a callable for the update extension binding method over gRPC. + + Updates the parameters of the specified ``ExtensionBinding`` + resource. + + Returns: + Callable[[~.UpdateExtensionBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_extension_binding" not in self._stubs: + self._stubs["update_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/UpdateExtensionBinding", + request_serializer=dep.UpdateExtensionBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_extension_binding"] + + @property + def delete_extension_binding( + self, + ) -> Callable[[dep.DeleteExtensionBindingRequest], operations_pb2.Operation]: + r"""Return a callable for the delete extension binding method over gRPC. + + Deletes the specified ``ExtensionBinding`` resource. + + Returns: + Callable[[~.DeleteExtensionBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_extension_binding" not in self._stubs: + self._stubs["delete_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/DeleteExtensionBinding", + request_serializer=dep.DeleteExtensionBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_extension_binding"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("DepServiceGrpcTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/grpc_asyncio.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..66a5c17f2bc3 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/grpc_asyncio.py @@ -0,0 +1,1117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.network_services_v1beta1.types import dep + +from .base import DEFAULT_CLIENT_INFO, DepServiceTransport +from .grpc import DepServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DepServiceGrpcAsyncIOTransport(DepServiceTransport): + """gRPC AsyncIO backend transport for DepService. + + Service describing handlers for resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_lb_traffic_extensions( + self, + ) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], + Awaitable[dep.ListLbTrafficExtensionsResponse], + ]: + r"""Return a callable for the list lb traffic extensions method over gRPC. + + Lists ``LbTrafficExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbTrafficExtensionsRequest], + Awaitable[~.ListLbTrafficExtensionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_lb_traffic_extensions" not in self._stubs: + self._stubs["list_lb_traffic_extensions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/ListLbTrafficExtensions", + request_serializer=dep.ListLbTrafficExtensionsRequest.serialize, + response_deserializer=dep.ListLbTrafficExtensionsResponse.deserialize, + ) + ) + return self._stubs["list_lb_traffic_extensions"] + + @property + def get_lb_traffic_extension( + self, + ) -> Callable[ + [dep.GetLbTrafficExtensionRequest], Awaitable[dep.LbTrafficExtension] + ]: + r"""Return a callable for the get lb traffic extension method over gRPC. + + Gets details of the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.GetLbTrafficExtensionRequest], + Awaitable[~.LbTrafficExtension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_lb_traffic_extension" not in self._stubs: + self._stubs["get_lb_traffic_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/GetLbTrafficExtension", + request_serializer=dep.GetLbTrafficExtensionRequest.serialize, + response_deserializer=dep.LbTrafficExtension.deserialize, + ) + return self._stubs["get_lb_traffic_extension"] + + @property + def create_lb_traffic_extension( + self, + ) -> Callable[ + [dep.CreateLbTrafficExtensionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create lb traffic extension method over gRPC. + + Creates a new ``LbTrafficExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbTrafficExtensionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_lb_traffic_extension" not in self._stubs: + self._stubs["create_lb_traffic_extension"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/CreateLbTrafficExtension", + request_serializer=dep.CreateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_lb_traffic_extension"] + + @property + def update_lb_traffic_extension( + self, + ) -> Callable[ + [dep.UpdateLbTrafficExtensionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update lb traffic extension method over gRPC. + + Updates the parameters of the specified ``LbTrafficExtension`` + resource. + + Returns: + Callable[[~.UpdateLbTrafficExtensionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_lb_traffic_extension" not in self._stubs: + self._stubs["update_lb_traffic_extension"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/UpdateLbTrafficExtension", + request_serializer=dep.UpdateLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_lb_traffic_extension"] + + @property + def delete_lb_traffic_extension( + self, + ) -> Callable[ + [dep.DeleteLbTrafficExtensionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete lb traffic extension method over gRPC. + + Deletes the specified ``LbTrafficExtension`` resource. + + Returns: + Callable[[~.DeleteLbTrafficExtensionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_lb_traffic_extension" not in self._stubs: + self._stubs["delete_lb_traffic_extension"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/DeleteLbTrafficExtension", + request_serializer=dep.DeleteLbTrafficExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_lb_traffic_extension"] + + @property + def list_lb_route_extensions( + self, + ) -> Callable[ + [dep.ListLbRouteExtensionsRequest], Awaitable[dep.ListLbRouteExtensionsResponse] + ]: + r"""Return a callable for the list lb route extensions method over gRPC. + + Lists ``LbRouteExtension`` resources in a given project and + location. + + Returns: + Callable[[~.ListLbRouteExtensionsRequest], + Awaitable[~.ListLbRouteExtensionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_lb_route_extensions" not in self._stubs: + self._stubs["list_lb_route_extensions"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/ListLbRouteExtensions", + request_serializer=dep.ListLbRouteExtensionsRequest.serialize, + response_deserializer=dep.ListLbRouteExtensionsResponse.deserialize, + ) + return self._stubs["list_lb_route_extensions"] + + @property + def get_lb_route_extension( + self, + ) -> Callable[[dep.GetLbRouteExtensionRequest], Awaitable[dep.LbRouteExtension]]: + r"""Return a callable for the get lb route extension method over gRPC. + + Gets details of the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.GetLbRouteExtensionRequest], + Awaitable[~.LbRouteExtension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_lb_route_extension" not in self._stubs: + self._stubs["get_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/GetLbRouteExtension", + request_serializer=dep.GetLbRouteExtensionRequest.serialize, + response_deserializer=dep.LbRouteExtension.deserialize, + ) + return self._stubs["get_lb_route_extension"] + + @property + def create_lb_route_extension( + self, + ) -> Callable[ + [dep.CreateLbRouteExtensionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create lb route extension method over gRPC. + + Creates a new ``LbRouteExtension`` resource in a given project + and location. + + Returns: + Callable[[~.CreateLbRouteExtensionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_lb_route_extension" not in self._stubs: + self._stubs["create_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/CreateLbRouteExtension", + request_serializer=dep.CreateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_lb_route_extension"] + + @property + def update_lb_route_extension( + self, + ) -> Callable[ + [dep.UpdateLbRouteExtensionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update lb route extension method over gRPC. + + Updates the parameters of the specified ``LbRouteExtension`` + resource. + + Returns: + Callable[[~.UpdateLbRouteExtensionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_lb_route_extension" not in self._stubs: + self._stubs["update_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/UpdateLbRouteExtension", + request_serializer=dep.UpdateLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_lb_route_extension"] + + @property + def delete_lb_route_extension( + self, + ) -> Callable[ + [dep.DeleteLbRouteExtensionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete lb route extension method over gRPC. + + Deletes the specified ``LbRouteExtension`` resource. + + Returns: + Callable[[~.DeleteLbRouteExtensionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_lb_route_extension" not in self._stubs: + self._stubs["delete_lb_route_extension"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/DeleteLbRouteExtension", + request_serializer=dep.DeleteLbRouteExtensionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_lb_route_extension"] + + @property + def list_extension_bindings( + self, + ) -> Callable[ + [dep.ListExtensionBindingsRequest], Awaitable[dep.ListExtensionBindingsResponse] + ]: + r"""Return a callable for the list extension bindings method over gRPC. + + Lists ``ExtensionBinding`` resources in a given project and + location. + + Returns: + Callable[[~.ListExtensionBindingsRequest], + Awaitable[~.ListExtensionBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_extension_bindings" not in self._stubs: + self._stubs["list_extension_bindings"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/ListExtensionBindings", + request_serializer=dep.ListExtensionBindingsRequest.serialize, + response_deserializer=dep.ListExtensionBindingsResponse.deserialize, + ) + return self._stubs["list_extension_bindings"] + + @property + def get_extension_binding( + self, + ) -> Callable[[dep.GetExtensionBindingRequest], Awaitable[dep.ExtensionBinding]]: + r"""Return a callable for the get extension binding method over gRPC. + + Gets details of the specified ``ExtensionBinding`` resource. + + Returns: + Callable[[~.GetExtensionBindingRequest], + Awaitable[~.ExtensionBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_extension_binding" not in self._stubs: + self._stubs["get_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/GetExtensionBinding", + request_serializer=dep.GetExtensionBindingRequest.serialize, + response_deserializer=dep.ExtensionBinding.deserialize, + ) + return self._stubs["get_extension_binding"] + + @property + def create_extension_binding( + self, + ) -> Callable[ + [dep.CreateExtensionBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create extension binding method over gRPC. + + Creates a new ``ExtensionBinding`` resource in a given project + and location. + + Returns: + Callable[[~.CreateExtensionBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_extension_binding" not in self._stubs: + self._stubs["create_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/CreateExtensionBinding", + request_serializer=dep.CreateExtensionBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_extension_binding"] + + @property + def update_extension_binding( + self, + ) -> Callable[ + [dep.UpdateExtensionBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update extension binding method over gRPC. + + Updates the parameters of the specified ``ExtensionBinding`` + resource. + + Returns: + Callable[[~.UpdateExtensionBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_extension_binding" not in self._stubs: + self._stubs["update_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/UpdateExtensionBinding", + request_serializer=dep.UpdateExtensionBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_extension_binding"] + + @property + def delete_extension_binding( + self, + ) -> Callable[ + [dep.DeleteExtensionBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete extension binding method over gRPC. + + Deletes the specified ``ExtensionBinding`` resource. + + Returns: + Callable[[~.DeleteExtensionBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_extension_binding" not in self._stubs: + self._stubs["delete_extension_binding"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.DepService/DeleteExtensionBinding", + request_serializer=dep.DeleteExtensionBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_extension_binding"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_lb_traffic_extensions: self._wrap_method( + self.list_lb_traffic_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_traffic_extension: self._wrap_method( + self.get_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_traffic_extension: self._wrap_method( + self.create_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_traffic_extension: self._wrap_method( + self.update_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_traffic_extension: self._wrap_method( + self.delete_lb_traffic_extension, + default_timeout=None, + client_info=client_info, + ), + self.list_lb_route_extensions: self._wrap_method( + self.list_lb_route_extensions, + default_timeout=None, + client_info=client_info, + ), + self.get_lb_route_extension: self._wrap_method( + self.get_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.create_lb_route_extension: self._wrap_method( + self.create_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.update_lb_route_extension: self._wrap_method( + self.update_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.delete_lb_route_extension: self._wrap_method( + self.delete_lb_route_extension, + default_timeout=None, + client_info=client_info, + ), + self.list_extension_bindings: self._wrap_method( + self.list_extension_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_extension_binding: self._wrap_method( + self.get_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_extension_binding: self._wrap_method( + self.create_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_extension_binding: self._wrap_method( + self.update_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_extension_binding: self._wrap_method( + self.delete_extension_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("DepServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/rest.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/rest.py new file mode 100644 index 000000000000..dbdaba2762e2 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/rest.py @@ -0,0 +1,4897 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.network_services_v1beta1._compat import transcode_request +from google.cloud.network_services_v1beta1.types import dep + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseDepServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DepServiceRestInterceptor: + """Interceptor for DepService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the DepServiceRestTransport. + + .. code-block:: python + class MyCustomDepServiceInterceptor(DepServiceRestInterceptor): + def pre_create_extension_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_extension_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_extension_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_extension_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_extension_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_extension_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_extension_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_extension_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_lb_route_extensions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_lb_route_extensions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_lb_traffic_extensions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_lb_traffic_extensions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_extension_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_extension_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_lb_route_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_lb_route_extension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_lb_traffic_extension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_lb_traffic_extension(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DepServiceRestTransport(interceptor=MyCustomDepServiceInterceptor()) + client = DepServiceClient(transport=transport) + + + """ + + def pre_create_extension_binding( + self, + request: dep.CreateExtensionBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.CreateExtensionBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_extension_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_create_extension_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_extension_binding + + DEPRECATED. Please use the `post_create_extension_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_create_extension_binding` interceptor runs + before the `post_create_extension_binding_with_metadata` interceptor. + """ + return response + + def post_create_extension_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_extension_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_create_extension_binding_with_metadata` + interceptor in new development instead of the `post_create_extension_binding` interceptor. + When both interceptors are used, this `post_create_extension_binding_with_metadata` interceptor runs after the + `post_create_extension_binding` interceptor. The (possibly modified) response returned by + `post_create_extension_binding` will be passed to + `post_create_extension_binding_with_metadata`. + """ + return response, metadata + + def pre_create_lb_route_extension( + self, + request: dep.CreateLbRouteExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.CreateLbRouteExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_create_lb_route_extension( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_lb_route_extension + + DEPRECATED. Please use the `post_create_lb_route_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_create_lb_route_extension` interceptor runs + before the `post_create_lb_route_extension_with_metadata` interceptor. + """ + return response + + def post_create_lb_route_extension_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_lb_route_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_create_lb_route_extension_with_metadata` + interceptor in new development instead of the `post_create_lb_route_extension` interceptor. + When both interceptors are used, this `post_create_lb_route_extension_with_metadata` interceptor runs after the + `post_create_lb_route_extension` interceptor. The (possibly modified) response returned by + `post_create_lb_route_extension` will be passed to + `post_create_lb_route_extension_with_metadata`. + """ + return response, metadata + + def pre_create_lb_traffic_extension( + self, + request: dep.CreateLbTrafficExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.CreateLbTrafficExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_create_lb_traffic_extension( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_lb_traffic_extension + + DEPRECATED. Please use the `post_create_lb_traffic_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_create_lb_traffic_extension` interceptor runs + before the `post_create_lb_traffic_extension_with_metadata` interceptor. + """ + return response + + def post_create_lb_traffic_extension_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_lb_traffic_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_create_lb_traffic_extension_with_metadata` + interceptor in new development instead of the `post_create_lb_traffic_extension` interceptor. + When both interceptors are used, this `post_create_lb_traffic_extension_with_metadata` interceptor runs after the + `post_create_lb_traffic_extension` interceptor. The (possibly modified) response returned by + `post_create_lb_traffic_extension` will be passed to + `post_create_lb_traffic_extension_with_metadata`. + """ + return response, metadata + + def pre_delete_extension_binding( + self, + request: dep.DeleteExtensionBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.DeleteExtensionBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_extension_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_delete_extension_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_extension_binding + + DEPRECATED. Please use the `post_delete_extension_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_delete_extension_binding` interceptor runs + before the `post_delete_extension_binding_with_metadata` interceptor. + """ + return response + + def post_delete_extension_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_extension_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_delete_extension_binding_with_metadata` + interceptor in new development instead of the `post_delete_extension_binding` interceptor. + When both interceptors are used, this `post_delete_extension_binding_with_metadata` interceptor runs after the + `post_delete_extension_binding` interceptor. The (possibly modified) response returned by + `post_delete_extension_binding` will be passed to + `post_delete_extension_binding_with_metadata`. + """ + return response, metadata + + def pre_delete_lb_route_extension( + self, + request: dep.DeleteLbRouteExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.DeleteLbRouteExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_delete_lb_route_extension( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_lb_route_extension + + DEPRECATED. Please use the `post_delete_lb_route_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_delete_lb_route_extension` interceptor runs + before the `post_delete_lb_route_extension_with_metadata` interceptor. + """ + return response + + def post_delete_lb_route_extension_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_lb_route_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_delete_lb_route_extension_with_metadata` + interceptor in new development instead of the `post_delete_lb_route_extension` interceptor. + When both interceptors are used, this `post_delete_lb_route_extension_with_metadata` interceptor runs after the + `post_delete_lb_route_extension` interceptor. The (possibly modified) response returned by + `post_delete_lb_route_extension` will be passed to + `post_delete_lb_route_extension_with_metadata`. + """ + return response, metadata + + def pre_delete_lb_traffic_extension( + self, + request: dep.DeleteLbTrafficExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.DeleteLbTrafficExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_delete_lb_traffic_extension( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_lb_traffic_extension + + DEPRECATED. Please use the `post_delete_lb_traffic_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_delete_lb_traffic_extension` interceptor runs + before the `post_delete_lb_traffic_extension_with_metadata` interceptor. + """ + return response + + def post_delete_lb_traffic_extension_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_lb_traffic_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_delete_lb_traffic_extension_with_metadata` + interceptor in new development instead of the `post_delete_lb_traffic_extension` interceptor. + When both interceptors are used, this `post_delete_lb_traffic_extension_with_metadata` interceptor runs after the + `post_delete_lb_traffic_extension` interceptor. The (possibly modified) response returned by + `post_delete_lb_traffic_extension` will be passed to + `post_delete_lb_traffic_extension_with_metadata`. + """ + return response, metadata + + def pre_get_extension_binding( + self, + request: dep.GetExtensionBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[dep.GetExtensionBindingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_extension_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_extension_binding( + self, response: dep.ExtensionBinding + ) -> dep.ExtensionBinding: + """Post-rpc interceptor for get_extension_binding + + DEPRECATED. Please use the `post_get_extension_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_get_extension_binding` interceptor runs + before the `post_get_extension_binding_with_metadata` interceptor. + """ + return response + + def post_get_extension_binding_with_metadata( + self, + response: dep.ExtensionBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[dep.ExtensionBinding, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_extension_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_get_extension_binding_with_metadata` + interceptor in new development instead of the `post_get_extension_binding` interceptor. + When both interceptors are used, this `post_get_extension_binding_with_metadata` interceptor runs after the + `post_get_extension_binding` interceptor. The (possibly modified) response returned by + `post_get_extension_binding` will be passed to + `post_get_extension_binding_with_metadata`. + """ + return response, metadata + + def pre_get_lb_route_extension( + self, + request: dep.GetLbRouteExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[dep.GetLbRouteExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_lb_route_extension( + self, response: dep.LbRouteExtension + ) -> dep.LbRouteExtension: + """Post-rpc interceptor for get_lb_route_extension + + DEPRECATED. Please use the `post_get_lb_route_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_get_lb_route_extension` interceptor runs + before the `post_get_lb_route_extension_with_metadata` interceptor. + """ + return response + + def post_get_lb_route_extension_with_metadata( + self, + response: dep.LbRouteExtension, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[dep.LbRouteExtension, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_lb_route_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_get_lb_route_extension_with_metadata` + interceptor in new development instead of the `post_get_lb_route_extension` interceptor. + When both interceptors are used, this `post_get_lb_route_extension_with_metadata` interceptor runs after the + `post_get_lb_route_extension` interceptor. The (possibly modified) response returned by + `post_get_lb_route_extension` will be passed to + `post_get_lb_route_extension_with_metadata`. + """ + return response, metadata + + def pre_get_lb_traffic_extension( + self, + request: dep.GetLbTrafficExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.GetLbTrafficExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_lb_traffic_extension( + self, response: dep.LbTrafficExtension + ) -> dep.LbTrafficExtension: + """Post-rpc interceptor for get_lb_traffic_extension + + DEPRECATED. Please use the `post_get_lb_traffic_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_get_lb_traffic_extension` interceptor runs + before the `post_get_lb_traffic_extension_with_metadata` interceptor. + """ + return response + + def post_get_lb_traffic_extension_with_metadata( + self, + response: dep.LbTrafficExtension, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[dep.LbTrafficExtension, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_lb_traffic_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_get_lb_traffic_extension_with_metadata` + interceptor in new development instead of the `post_get_lb_traffic_extension` interceptor. + When both interceptors are used, this `post_get_lb_traffic_extension_with_metadata` interceptor runs after the + `post_get_lb_traffic_extension` interceptor. The (possibly modified) response returned by + `post_get_lb_traffic_extension` will be passed to + `post_get_lb_traffic_extension_with_metadata`. + """ + return response, metadata + + def pre_list_extension_bindings( + self, + request: dep.ListExtensionBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.ListExtensionBindingsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_extension_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_list_extension_bindings( + self, response: dep.ListExtensionBindingsResponse + ) -> dep.ListExtensionBindingsResponse: + """Post-rpc interceptor for list_extension_bindings + + DEPRECATED. Please use the `post_list_extension_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_list_extension_bindings` interceptor runs + before the `post_list_extension_bindings_with_metadata` interceptor. + """ + return response + + def post_list_extension_bindings_with_metadata( + self, + response: dep.ListExtensionBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.ListExtensionBindingsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_extension_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_list_extension_bindings_with_metadata` + interceptor in new development instead of the `post_list_extension_bindings` interceptor. + When both interceptors are used, this `post_list_extension_bindings_with_metadata` interceptor runs after the + `post_list_extension_bindings` interceptor. The (possibly modified) response returned by + `post_list_extension_bindings` will be passed to + `post_list_extension_bindings_with_metadata`. + """ + return response, metadata + + def pre_list_lb_route_extensions( + self, + request: dep.ListLbRouteExtensionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.ListLbRouteExtensionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_lb_route_extensions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_list_lb_route_extensions( + self, response: dep.ListLbRouteExtensionsResponse + ) -> dep.ListLbRouteExtensionsResponse: + """Post-rpc interceptor for list_lb_route_extensions + + DEPRECATED. Please use the `post_list_lb_route_extensions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_list_lb_route_extensions` interceptor runs + before the `post_list_lb_route_extensions_with_metadata` interceptor. + """ + return response + + def post_list_lb_route_extensions_with_metadata( + self, + response: dep.ListLbRouteExtensionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.ListLbRouteExtensionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_lb_route_extensions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_list_lb_route_extensions_with_metadata` + interceptor in new development instead of the `post_list_lb_route_extensions` interceptor. + When both interceptors are used, this `post_list_lb_route_extensions_with_metadata` interceptor runs after the + `post_list_lb_route_extensions` interceptor. The (possibly modified) response returned by + `post_list_lb_route_extensions` will be passed to + `post_list_lb_route_extensions_with_metadata`. + """ + return response, metadata + + def pre_list_lb_traffic_extensions( + self, + request: dep.ListLbTrafficExtensionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.ListLbTrafficExtensionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_lb_traffic_extensions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_list_lb_traffic_extensions( + self, response: dep.ListLbTrafficExtensionsResponse + ) -> dep.ListLbTrafficExtensionsResponse: + """Post-rpc interceptor for list_lb_traffic_extensions + + DEPRECATED. Please use the `post_list_lb_traffic_extensions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_list_lb_traffic_extensions` interceptor runs + before the `post_list_lb_traffic_extensions_with_metadata` interceptor. + """ + return response + + def post_list_lb_traffic_extensions_with_metadata( + self, + response: dep.ListLbTrafficExtensionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.ListLbTrafficExtensionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_lb_traffic_extensions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_list_lb_traffic_extensions_with_metadata` + interceptor in new development instead of the `post_list_lb_traffic_extensions` interceptor. + When both interceptors are used, this `post_list_lb_traffic_extensions_with_metadata` interceptor runs after the + `post_list_lb_traffic_extensions` interceptor. The (possibly modified) response returned by + `post_list_lb_traffic_extensions` will be passed to + `post_list_lb_traffic_extensions_with_metadata`. + """ + return response, metadata + + def pre_update_extension_binding( + self, + request: dep.UpdateExtensionBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.UpdateExtensionBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_extension_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_update_extension_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_extension_binding + + DEPRECATED. Please use the `post_update_extension_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_update_extension_binding` interceptor runs + before the `post_update_extension_binding_with_metadata` interceptor. + """ + return response + + def post_update_extension_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_extension_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_update_extension_binding_with_metadata` + interceptor in new development instead of the `post_update_extension_binding` interceptor. + When both interceptors are used, this `post_update_extension_binding_with_metadata` interceptor runs after the + `post_update_extension_binding` interceptor. The (possibly modified) response returned by + `post_update_extension_binding` will be passed to + `post_update_extension_binding_with_metadata`. + """ + return response, metadata + + def pre_update_lb_route_extension( + self, + request: dep.UpdateLbRouteExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.UpdateLbRouteExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_lb_route_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_update_lb_route_extension( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_lb_route_extension + + DEPRECATED. Please use the `post_update_lb_route_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_update_lb_route_extension` interceptor runs + before the `post_update_lb_route_extension_with_metadata` interceptor. + """ + return response + + def post_update_lb_route_extension_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_lb_route_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_update_lb_route_extension_with_metadata` + interceptor in new development instead of the `post_update_lb_route_extension` interceptor. + When both interceptors are used, this `post_update_lb_route_extension_with_metadata` interceptor runs after the + `post_update_lb_route_extension` interceptor. The (possibly modified) response returned by + `post_update_lb_route_extension` will be passed to + `post_update_lb_route_extension_with_metadata`. + """ + return response, metadata + + def pre_update_lb_traffic_extension( + self, + request: dep.UpdateLbTrafficExtensionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dep.UpdateLbTrafficExtensionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_lb_traffic_extension + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_update_lb_traffic_extension( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_lb_traffic_extension + + DEPRECATED. Please use the `post_update_lb_traffic_extension_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DepService server but before + it is returned to user code. This `post_update_lb_traffic_extension` interceptor runs + before the `post_update_lb_traffic_extension_with_metadata` interceptor. + """ + return response + + def post_update_lb_traffic_extension_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_lb_traffic_extension + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DepService server but before it is returned to user code. + + We recommend only using this `post_update_lb_traffic_extension_with_metadata` + interceptor in new development instead of the `post_update_lb_traffic_extension` interceptor. + When both interceptors are used, this `post_update_lb_traffic_extension_with_metadata` interceptor runs after the + `post_update_lb_traffic_extension` interceptor. The (possibly modified) response returned by + `post_update_lb_traffic_extension` will be passed to + `post_update_lb_traffic_extension_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DepService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the DepService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DepServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DepServiceRestInterceptor + + +class DepServiceRestTransport(_BaseDepServiceRestTransport): + """REST backend synchronous transport for DepService. + + Service describing handlers for resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[DepServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[DepServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DepServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateExtensionBinding( + _BaseDepServiceRestTransport._BaseCreateExtensionBinding, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.CreateExtensionBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: dep.CreateExtensionBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create extension binding method over HTTP. + + Args: + request (~.dep.CreateExtensionBindingRequest): + The request object. Request used by the ``CreateExtensionBinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseCreateExtensionBinding._get_http_options() + request, metadata = self._interceptor.pre_create_extension_binding( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseCreateExtensionBinding, + "_BaseCreateExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.CreateExtensionBinding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "CreateExtensionBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._CreateExtensionBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_extension_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_extension_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.create_extension_binding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "CreateExtensionBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateLbRouteExtension( + _BaseDepServiceRestTransport._BaseCreateLbRouteExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.CreateLbRouteExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: dep.CreateLbRouteExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create lb route extension method over HTTP. + + Args: + request (~.dep.CreateLbRouteExtensionRequest): + The request object. Message for creating a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseCreateLbRouteExtension._get_http_options() + request, metadata = self._interceptor.pre_create_lb_route_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseCreateLbRouteExtension, + "_BaseCreateLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.CreateLbRouteExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "CreateLbRouteExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._CreateLbRouteExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_lb_route_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_lb_route_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.create_lb_route_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "CreateLbRouteExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateLbTrafficExtension( + _BaseDepServiceRestTransport._BaseCreateLbTrafficExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.CreateLbTrafficExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: dep.CreateLbTrafficExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create lb traffic + extension method over HTTP. + + Args: + request (~.dep.CreateLbTrafficExtensionRequest): + The request object. Message for creating a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseCreateLbTrafficExtension._get_http_options() + request, metadata = self._interceptor.pre_create_lb_traffic_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseCreateLbTrafficExtension, + "_BaseCreateLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.CreateLbTrafficExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "CreateLbTrafficExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._CreateLbTrafficExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_lb_traffic_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_lb_traffic_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.create_lb_traffic_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "CreateLbTrafficExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteExtensionBinding( + _BaseDepServiceRestTransport._BaseDeleteExtensionBinding, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.DeleteExtensionBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.DeleteExtensionBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete extension binding method over HTTP. + + Args: + request (~.dep.DeleteExtensionBindingRequest): + The request object. Request used by the ``DeleteExtensionBinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseDeleteExtensionBinding._get_http_options() + request, metadata = self._interceptor.pre_delete_extension_binding( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseDeleteExtensionBinding, + "_BaseDeleteExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.DeleteExtensionBinding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "DeleteExtensionBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._DeleteExtensionBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_extension_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_extension_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.delete_extension_binding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "DeleteExtensionBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteLbRouteExtension( + _BaseDepServiceRestTransport._BaseDeleteLbRouteExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.DeleteLbRouteExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.DeleteLbRouteExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete lb route extension method over HTTP. + + Args: + request (~.dep.DeleteLbRouteExtensionRequest): + The request object. Message for deleting a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseDeleteLbRouteExtension._get_http_options() + request, metadata = self._interceptor.pre_delete_lb_route_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseDeleteLbRouteExtension, + "_BaseDeleteLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.DeleteLbRouteExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "DeleteLbRouteExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._DeleteLbRouteExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_lb_route_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_lb_route_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.delete_lb_route_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "DeleteLbRouteExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteLbTrafficExtension( + _BaseDepServiceRestTransport._BaseDeleteLbTrafficExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.DeleteLbTrafficExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.DeleteLbTrafficExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete lb traffic + extension method over HTTP. + + Args: + request (~.dep.DeleteLbTrafficExtensionRequest): + The request object. Message for deleting a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseDeleteLbTrafficExtension._get_http_options() + request, metadata = self._interceptor.pre_delete_lb_traffic_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseDeleteLbTrafficExtension, + "_BaseDeleteLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.DeleteLbTrafficExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "DeleteLbTrafficExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._DeleteLbTrafficExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_lb_traffic_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_lb_traffic_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.delete_lb_traffic_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "DeleteLbTrafficExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetExtensionBinding( + _BaseDepServiceRestTransport._BaseGetExtensionBinding, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.GetExtensionBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.GetExtensionBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.ExtensionBinding: + r"""Call the get extension binding method over HTTP. + + Args: + request (~.dep.GetExtensionBindingRequest): + The request object. Request used by the ``GetExtensionBinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dep.ExtensionBinding: + ``ExtensionBinding`` is a resource representing the + attachment of an extension to a service. + + """ + + http_options = _BaseDepServiceRestTransport._BaseGetExtensionBinding._get_http_options() + request, metadata = self._interceptor.pre_get_extension_binding( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseGetExtensionBinding, + "_BaseGetExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.GetExtensionBinding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetExtensionBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._GetExtensionBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.ExtensionBinding() + pb_resp = dep.ExtensionBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_extension_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_extension_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dep.ExtensionBinding.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.get_extension_binding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetExtensionBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetLbRouteExtension( + _BaseDepServiceRestTransport._BaseGetLbRouteExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.GetLbRouteExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.GetLbRouteExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.LbRouteExtension: + r"""Call the get lb route extension method over HTTP. + + Args: + request (~.dep.GetLbRouteExtensionRequest): + The request object. Message for getting a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dep.LbRouteExtension: + ``LbRouteExtension`` is a resource that lets you control + where traffic is routed to for a given request. + + """ + + http_options = _BaseDepServiceRestTransport._BaseGetLbRouteExtension._get_http_options() + request, metadata = self._interceptor.pre_get_lb_route_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseGetLbRouteExtension, + "_BaseGetLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.GetLbRouteExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetLbRouteExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._GetLbRouteExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.LbRouteExtension() + pb_resp = dep.LbRouteExtension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_lb_route_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_lb_route_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dep.LbRouteExtension.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.get_lb_route_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetLbRouteExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetLbTrafficExtension( + _BaseDepServiceRestTransport._BaseGetLbTrafficExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.GetLbTrafficExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.GetLbTrafficExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.LbTrafficExtension: + r"""Call the get lb traffic extension method over HTTP. + + Args: + request (~.dep.GetLbTrafficExtensionRequest): + The request object. Message for getting a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dep.LbTrafficExtension: + ``LbTrafficExtension`` is a resource that lets the + extension service modify the headers and payloads of + both requests and responses without impacting the choice + of backend services or any other security policies + associated with the backend service. + + """ + + http_options = _BaseDepServiceRestTransport._BaseGetLbTrafficExtension._get_http_options() + request, metadata = self._interceptor.pre_get_lb_traffic_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseGetLbTrafficExtension, + "_BaseGetLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.GetLbTrafficExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetLbTrafficExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._GetLbTrafficExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.LbTrafficExtension() + pb_resp = dep.LbTrafficExtension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_lb_traffic_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_lb_traffic_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dep.LbTrafficExtension.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.get_lb_traffic_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetLbTrafficExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListExtensionBindings( + _BaseDepServiceRestTransport._BaseListExtensionBindings, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.ListExtensionBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.ListExtensionBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.ListExtensionBindingsResponse: + r"""Call the list extension bindings method over HTTP. + + Args: + request (~.dep.ListExtensionBindingsRequest): + The request object. Request used with the ``ListExtensionBindings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dep.ListExtensionBindingsResponse: + Response returned by the ``ListExtensionBindings`` + method. + + """ + + http_options = _BaseDepServiceRestTransport._BaseListExtensionBindings._get_http_options() + request, metadata = self._interceptor.pre_list_extension_bindings( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseListExtensionBindings, + "_BaseListExtensionBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.ListExtensionBindings", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListExtensionBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._ListExtensionBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.ListExtensionBindingsResponse() + pb_resp = dep.ListExtensionBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_extension_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_extension_bindings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dep.ListExtensionBindingsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.list_extension_bindings", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListExtensionBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListLbRouteExtensions( + _BaseDepServiceRestTransport._BaseListLbRouteExtensions, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.ListLbRouteExtensions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.ListLbRouteExtensionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.ListLbRouteExtensionsResponse: + r"""Call the list lb route extensions method over HTTP. + + Args: + request (~.dep.ListLbRouteExtensionsRequest): + The request object. Message for requesting list of ``LbRouteExtension`` + resources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dep.ListLbRouteExtensionsResponse: + Message for response to listing ``LbRouteExtension`` + resources. + + """ + + http_options = _BaseDepServiceRestTransport._BaseListLbRouteExtensions._get_http_options() + request, metadata = self._interceptor.pre_list_lb_route_extensions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseListLbRouteExtensions, + "_BaseListLbRouteExtensions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.ListLbRouteExtensions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListLbRouteExtensions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._ListLbRouteExtensions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.ListLbRouteExtensionsResponse() + pb_resp = dep.ListLbRouteExtensionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_lb_route_extensions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_lb_route_extensions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dep.ListLbRouteExtensionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.list_lb_route_extensions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListLbRouteExtensions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListLbTrafficExtensions( + _BaseDepServiceRestTransport._BaseListLbTrafficExtensions, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.ListLbTrafficExtensions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: dep.ListLbTrafficExtensionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dep.ListLbTrafficExtensionsResponse: + r"""Call the list lb traffic + extensions method over HTTP. + + Args: + request (~.dep.ListLbTrafficExtensionsRequest): + The request object. Message for requesting list of ``LbTrafficExtension`` + resources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.dep.ListLbTrafficExtensionsResponse: + Message for response to listing ``LbTrafficExtension`` + resources. + + """ + + http_options = _BaseDepServiceRestTransport._BaseListLbTrafficExtensions._get_http_options() + request, metadata = self._interceptor.pre_list_lb_traffic_extensions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseListLbTrafficExtensions, + "_BaseListLbTrafficExtensions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.ListLbTrafficExtensions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListLbTrafficExtensions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._ListLbTrafficExtensions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dep.ListLbTrafficExtensionsResponse() + pb_resp = dep.ListLbTrafficExtensionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_lb_traffic_extensions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_lb_traffic_extensions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dep.ListLbTrafficExtensionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.list_lb_traffic_extensions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListLbTrafficExtensions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateExtensionBinding( + _BaseDepServiceRestTransport._BaseUpdateExtensionBinding, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.UpdateExtensionBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: dep.UpdateExtensionBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update extension binding method over HTTP. + + Args: + request (~.dep.UpdateExtensionBindingRequest): + The request object. Request used by the ``UpdateExtensionBinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseUpdateExtensionBinding._get_http_options() + request, metadata = self._interceptor.pre_update_extension_binding( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseUpdateExtensionBinding, + "_BaseUpdateExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.UpdateExtensionBinding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "UpdateExtensionBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._UpdateExtensionBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_extension_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_extension_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.update_extension_binding", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "UpdateExtensionBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateLbRouteExtension( + _BaseDepServiceRestTransport._BaseUpdateLbRouteExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.UpdateLbRouteExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: dep.UpdateLbRouteExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update lb route extension method over HTTP. + + Args: + request (~.dep.UpdateLbRouteExtensionRequest): + The request object. Message for updating a ``LbRouteExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseUpdateLbRouteExtension._get_http_options() + request, metadata = self._interceptor.pre_update_lb_route_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseUpdateLbRouteExtension, + "_BaseUpdateLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.UpdateLbRouteExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "UpdateLbRouteExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._UpdateLbRouteExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_lb_route_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_lb_route_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.update_lb_route_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "UpdateLbRouteExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateLbTrafficExtension( + _BaseDepServiceRestTransport._BaseUpdateLbTrafficExtension, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.UpdateLbTrafficExtension") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: dep.UpdateLbTrafficExtensionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update lb traffic + extension method over HTTP. + + Args: + request (~.dep.UpdateLbTrafficExtensionRequest): + The request object. Message for updating a ``LbTrafficExtension`` resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDepServiceRestTransport._BaseUpdateLbTrafficExtension._get_http_options() + request, metadata = self._interceptor.pre_update_lb_traffic_extension( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseUpdateLbTrafficExtension, + "_BaseUpdateLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.UpdateLbTrafficExtension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "UpdateLbTrafficExtension", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._UpdateLbTrafficExtension._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_lb_traffic_extension(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_lb_traffic_extension_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceClient.update_lb_traffic_extension", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "UpdateLbTrafficExtension", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_extension_binding( + self, + ) -> Callable[[dep.CreateExtensionBindingRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateExtensionBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_lb_route_extension( + self, + ) -> Callable[[dep.CreateLbRouteExtensionRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateLbRouteExtension( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_lb_traffic_extension( + self, + ) -> Callable[[dep.CreateLbTrafficExtensionRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateLbTrafficExtension( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_extension_binding( + self, + ) -> Callable[[dep.DeleteExtensionBindingRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteExtensionBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_lb_route_extension( + self, + ) -> Callable[[dep.DeleteLbRouteExtensionRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteLbRouteExtension( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_lb_traffic_extension( + self, + ) -> Callable[[dep.DeleteLbTrafficExtensionRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteLbTrafficExtension( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_extension_binding( + self, + ) -> Callable[[dep.GetExtensionBindingRequest], dep.ExtensionBinding]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetExtensionBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_lb_route_extension( + self, + ) -> Callable[[dep.GetLbRouteExtensionRequest], dep.LbRouteExtension]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetLbRouteExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_lb_traffic_extension( + self, + ) -> Callable[[dep.GetLbTrafficExtensionRequest], dep.LbTrafficExtension]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetLbTrafficExtension(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_extension_bindings( + self, + ) -> Callable[ + [dep.ListExtensionBindingsRequest], dep.ListExtensionBindingsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListExtensionBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_lb_route_extensions( + self, + ) -> Callable[ + [dep.ListLbRouteExtensionsRequest], dep.ListLbRouteExtensionsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListLbRouteExtensions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_lb_traffic_extensions( + self, + ) -> Callable[ + [dep.ListLbTrafficExtensionsRequest], dep.ListLbTrafficExtensionsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListLbTrafficExtensions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_extension_binding( + self, + ) -> Callable[[dep.UpdateExtensionBindingRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateExtensionBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_lb_route_extension( + self, + ) -> Callable[[dep.UpdateLbRouteExtensionRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateLbRouteExtension( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_lb_traffic_extension( + self, + ) -> Callable[[dep.UpdateLbTrafficExtensionRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateLbTrafficExtension( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseDepServiceRestTransport._BaseGetLocation, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseGetLocation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseDepServiceRestTransport._BaseListLocations, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseListLocations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseDepServiceRestTransport._BaseGetIamPolicy, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseGetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseDepServiceRestTransport._BaseSetIamPolicy, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseSetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseDepServiceRestTransport._BaseTestIamPermissions, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseTestIamPermissions._get_http_options() + ) + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseTestIamPermissions, + "_BaseTestIamPermissions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseDepServiceRestTransport._BaseCancelOperation, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseCancelOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseDepServiceRestTransport._BaseDeleteOperation, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseDeleteOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseDeleteOperation, + "_BaseDeleteOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseDepServiceRestTransport._BaseGetOperation, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseGetOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseDepServiceRestTransport._BaseListOperations, DepServiceRestStub + ): + def __hash__(self): + return hash("DepServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseDepServiceRestTransport._BaseListOperations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDepServiceRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.DepServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DepServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.DepServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.DepService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DepServiceRestTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/rest_base.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/rest_base.py new file mode 100644 index 000000000000..6caa2dcc143d --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/dep_service/transports/rest_base.py @@ -0,0 +1,482 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.network_services_v1beta1.types import dep + +from .base import DEFAULT_CLIENT_INFO, DepServiceTransport + + +class _BaseDepServiceRestTransport(DepServiceTransport): + """Base REST backend transport for DepService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateExtensionBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "extensionBindingId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/extensionBindings", + "body": "extension_binding", + }, + ] + return http_options + + class _BaseCreateLbRouteExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "lbRouteExtensionId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/lbRouteExtensions", + "body": "lb_route_extension", + }, + ] + return http_options + + class _BaseCreateLbTrafficExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "lbTrafficExtensionId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/lbTrafficExtensions", + "body": "lb_traffic_extension", + }, + ] + return http_options + + class _BaseDeleteExtensionBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/extensionBindings/*}", + }, + ] + return http_options + + class _BaseDeleteLbRouteExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/lbRouteExtensions/*}", + }, + ] + return http_options + + class _BaseDeleteLbTrafficExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/lbTrafficExtensions/*}", + }, + ] + return http_options + + class _BaseGetExtensionBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/extensionBindings/*}", + }, + ] + return http_options + + class _BaseGetLbRouteExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/lbRouteExtensions/*}", + }, + ] + return http_options + + class _BaseGetLbTrafficExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/lbTrafficExtensions/*}", + }, + ] + return http_options + + class _BaseListExtensionBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/extensionBindings", + }, + ] + return http_options + + class _BaseListLbRouteExtensions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/lbRouteExtensions", + }, + ] + return http_options + + class _BaseListLbTrafficExtensions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/lbTrafficExtensions", + }, + ] + return http_options + + class _BaseUpdateExtensionBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{extension_binding.name=projects/*/locations/*/extensionBindings/*}", + "body": "extension_binding", + }, + ] + return http_options + + class _BaseUpdateLbRouteExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{lb_route_extension.name=projects/*/locations/*/lbRouteExtensions/*}", + "body": "lb_route_extension", + }, + ] + return http_options + + class _BaseUpdateLbTrafficExtension: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{lb_traffic_extension.name=projects/*/locations/*/lbTrafficExtensions/*}", + "body": "lb_traffic_extension", + }, + ] + return http_options + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}", + }, + ] + return http_options + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*}/locations", + }, + ] + return http_options + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/locations/*/endpointPolicies/*}:getIamPolicy", + }, + ] + return http_options + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/endpointPolicies/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/endpointPolicies/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseDepServiceRestTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/__init__.py new file mode 100644 index 000000000000..3ff22d18096c --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import NetworkServicesAsyncClient +from .client import NetworkServicesClient + +__all__ = ( + "NetworkServicesClient", + "NetworkServicesAsyncClient", +) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/async_client.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/async_client.py new file mode 100644 index 000000000000..f3d78c7eedcb --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/async_client.py @@ -0,0 +1,1711 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_services_v1beta1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_services_v1beta1.services.network_services import pagers +from google.cloud.network_services_v1beta1.types import common, endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +from .client import NetworkServicesClient +from .transports.base import DEFAULT_CLIENT_INFO, NetworkServicesTransport +from .transports.grpc_asyncio import NetworkServicesGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class NetworkServicesAsyncClient: + """Service describing handlers for resources.""" + + _client: NetworkServicesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = NetworkServicesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = NetworkServicesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = NetworkServicesClient._DEFAULT_UNIVERSE + + authorization_policy_path = staticmethod( + NetworkServicesClient.authorization_policy_path + ) + parse_authorization_policy_path = staticmethod( + NetworkServicesClient.parse_authorization_policy_path + ) + client_tls_policy_path = staticmethod(NetworkServicesClient.client_tls_policy_path) + parse_client_tls_policy_path = staticmethod( + NetworkServicesClient.parse_client_tls_policy_path + ) + endpoint_policy_path = staticmethod(NetworkServicesClient.endpoint_policy_path) + parse_endpoint_policy_path = staticmethod( + NetworkServicesClient.parse_endpoint_policy_path + ) + server_tls_policy_path = staticmethod(NetworkServicesClient.server_tls_policy_path) + parse_server_tls_policy_path = staticmethod( + NetworkServicesClient.parse_server_tls_policy_path + ) + common_billing_account_path = staticmethod( + NetworkServicesClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + NetworkServicesClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(NetworkServicesClient.common_folder_path) + parse_common_folder_path = staticmethod( + NetworkServicesClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + NetworkServicesClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + NetworkServicesClient.parse_common_organization_path + ) + common_project_path = staticmethod(NetworkServicesClient.common_project_path) + parse_common_project_path = staticmethod( + NetworkServicesClient.parse_common_project_path + ) + common_location_path = staticmethod(NetworkServicesClient.common_location_path) + parse_common_location_path = staticmethod( + NetworkServicesClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + NetworkServicesAsyncClient: The constructed client. + """ + sa_info_func = ( + NetworkServicesClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(NetworkServicesAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + NetworkServicesAsyncClient: The constructed client. + """ + sa_file_func = ( + NetworkServicesClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(NetworkServicesAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return NetworkServicesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> NetworkServicesTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkServicesTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = NetworkServicesClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, NetworkServicesTransport, Callable[..., NetworkServicesTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network services async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,NetworkServicesTransport,Callable[..., NetworkServicesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkServicesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = NetworkServicesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient`.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "credentialsType": None, + }, + ) + + async def list_endpoint_policies( + self, + request: Optional[ + Union[endpoint_policy.ListEndpointPoliciesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEndpointPoliciesAsyncPager: + r"""Lists EndpointPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.ListEndpointPoliciesRequest, dict]]): + The request object. Request used with the + ListEndpointPolicies method. + parent (:class:`str`): + Required. The project and location from which the + EndpointPolicies should be listed, specified in the + format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.network_services.pagers.ListEndpointPoliciesAsyncPager: + Response returned by the + ListEndpointPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, endpoint_policy.ListEndpointPoliciesRequest): + request = endpoint_policy.ListEndpointPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_endpoint_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEndpointPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_endpoint_policy( + self, + request: Optional[Union[endpoint_policy.GetEndpointPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> endpoint_policy.EndpointPolicy: + r"""Gets details of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.GetEndpointPolicyRequest, dict]]): + The request object. Request used with the + GetEndpointPolicy method. + name (:class:`str`): + Required. A name of the EndpointPolicy to get. Must be + in the format + ``projects/*/locations/global/endpointPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.EndpointPolicy: + EndpointPolicy is a resource that + helps apply desired configuration on the + endpoints that match specific criteria. + For example, this resource can be used + to apply "authentication config" an all + endpoints that serve on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, endpoint_policy.GetEndpointPolicyRequest): + request = endpoint_policy.GetEndpointPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_endpoint_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_endpoint_policy( + self, + request: Optional[ + Union[gcn_endpoint_policy.CreateEndpointPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + endpoint_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new EndpointPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = await client.create_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.CreateEndpointPolicyRequest, dict]]): + The request object. Request used with the + CreateEndpointPolicy method. + parent (:class:`str`): + Required. The parent resource of the EndpointPolicy. + Must be in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy (:class:`google.cloud.network_services_v1beta1.types.EndpointPolicy`): + Required. EndpointPolicy resource to + be created. + + This corresponds to the ``endpoint_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy_id (:class:`str`): + Required. Short name of the + EndpointPolicy resource to be created. + E.g. "CustomECS". + + This corresponds to the ``endpoint_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, endpoint_policy, endpoint_policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_endpoint_policy.CreateEndpointPolicyRequest): + request = gcn_endpoint_policy.CreateEndpointPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint_policy is not None: + request.endpoint_policy = endpoint_policy + if endpoint_policy_id is not None: + request.endpoint_policy_id = endpoint_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_endpoint_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcn_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_endpoint_policy( + self, + request: Optional[ + Union[gcn_endpoint_policy.UpdateEndpointPolicyRequest, dict] + ] = None, + *, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = await client.update_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.UpdateEndpointPolicyRequest, dict]]): + The request object. Request used with the + UpdateEndpointPolicy method. + endpoint_policy (:class:`google.cloud.network_services_v1beta1.types.EndpointPolicy`): + Required. Updated EndpointPolicy + resource. + + This corresponds to the ``endpoint_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the EndpointPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [endpoint_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_endpoint_policy.UpdateEndpointPolicyRequest): + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint_policy is not None: + request.endpoint_policy = endpoint_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_endpoint_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("endpoint_policy.name", request.endpoint_policy.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcn_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_endpoint_policy( + self, + request: Optional[ + Union[endpoint_policy.DeleteEndpointPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + async def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_services_v1beta1.types.DeleteEndpointPolicyRequest, dict]]): + The request object. Request used with the + DeleteEndpointPolicy method. + name (:class:`str`): + Required. A name of the EndpointPolicy to delete. Must + be in the format + ``projects/*/locations/global/endpointPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, endpoint_policy.DeleteEndpointPolicyRequest): + request = endpoint_policy.DeleteEndpointPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_endpoint_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "NetworkServicesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("NetworkServicesAsyncClient",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/client.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/client.py new file mode 100644 index 000000000000..5de62b990522 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/client.py @@ -0,0 +1,2075 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_services_v1beta1 import gapic_version as package_version +from google.cloud.network_services_v1beta1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_services_v1beta1.services.network_services import pagers +from google.cloud.network_services_v1beta1.types import common, endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +from .transports.base import DEFAULT_CLIENT_INFO, NetworkServicesTransport +from .transports.grpc import NetworkServicesGrpcTransport +from .transports.grpc_asyncio import NetworkServicesGrpcAsyncIOTransport +from .transports.rest import NetworkServicesRestTransport + + +class NetworkServicesClientMeta(type): + """Metaclass for the NetworkServices client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[NetworkServicesTransport]] + _transport_registry["grpc"] = NetworkServicesGrpcTransport + _transport_registry["grpc_asyncio"] = NetworkServicesGrpcAsyncIOTransport + _transport_registry["rest"] = NetworkServicesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[NetworkServicesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class NetworkServicesClient(metaclass=NetworkServicesClientMeta): + """Service describing handlers for resources.""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "networkservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "networkservices.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + NetworkServicesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + NetworkServicesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> NetworkServicesTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkServicesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def authorization_policy_path( + project: str, + location: str, + authorization_policy: str, + ) -> str: + """Returns a fully-qualified authorization_policy string.""" + return "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format( + project=project, + location=location, + authorization_policy=authorization_policy, + ) + + @staticmethod + def parse_authorization_policy_path(path: str) -> Dict[str, str]: + """Parses a authorization_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/authorizationPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def client_tls_policy_path( + project: str, + location: str, + client_tls_policy: str, + ) -> str: + """Returns a fully-qualified client_tls_policy string.""" + return "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format( + project=project, + location=location, + client_tls_policy=client_tls_policy, + ) + + @staticmethod + def parse_client_tls_policy_path(path: str) -> Dict[str, str]: + """Parses a client_tls_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/clientTlsPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def endpoint_policy_path( + project: str, + location: str, + endpoint_policy: str, + ) -> str: + """Returns a fully-qualified endpoint_policy string.""" + return "projects/{project}/locations/{location}/endpointPolicies/{endpoint_policy}".format( + project=project, + location=location, + endpoint_policy=endpoint_policy, + ) + + @staticmethod + def parse_endpoint_policy_path(path: str) -> Dict[str, str]: + """Parses a endpoint_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/endpointPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def server_tls_policy_path( + project: str, + location: str, + server_tls_policy: str, + ) -> str: + """Returns a fully-qualified server_tls_policy string.""" + return "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format( + project=project, + location=location, + server_tls_policy=server_tls_policy, + ) + + @staticmethod + def parse_server_tls_policy_path(path: str) -> Dict[str, str]: + """Parses a server_tls_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/serverTlsPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, NetworkServicesTransport, Callable[..., NetworkServicesTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network services client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,NetworkServicesTransport,Callable[..., NetworkServicesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkServicesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = NetworkServicesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=NetworkServicesClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, NetworkServicesTransport) + if transport_provided: + # transport is a NetworkServicesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(NetworkServicesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=NetworkServicesClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=NetworkServicesClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[NetworkServicesTransport], Callable[..., NetworkServicesTransport] + ] = ( + NetworkServicesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., NetworkServicesTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networkservices_v1beta1.NetworkServicesClient`.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "credentialsType": None, + }, + ) + + def list_endpoint_policies( + self, + request: Optional[ + Union[endpoint_policy.ListEndpointPoliciesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEndpointPoliciesPager: + r"""Lists EndpointPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.ListEndpointPoliciesRequest, dict]): + The request object. Request used with the + ListEndpointPolicies method. + parent (str): + Required. The project and location from which the + EndpointPolicies should be listed, specified in the + format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.services.network_services.pagers.ListEndpointPoliciesPager: + Response returned by the + ListEndpointPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, endpoint_policy.ListEndpointPoliciesRequest): + request = endpoint_policy.ListEndpointPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_endpoint_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEndpointPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_endpoint_policy( + self, + request: Optional[Union[endpoint_policy.GetEndpointPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> endpoint_policy.EndpointPolicy: + r"""Gets details of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.GetEndpointPolicyRequest, dict]): + The request object. Request used with the + GetEndpointPolicy method. + name (str): + Required. A name of the EndpointPolicy to get. Must be + in the format + ``projects/*/locations/global/endpointPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_services_v1beta1.types.EndpointPolicy: + EndpointPolicy is a resource that + helps apply desired configuration on the + endpoints that match specific criteria. + For example, this resource can be used + to apply "authentication config" an all + endpoints that serve on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, endpoint_policy.GetEndpointPolicyRequest): + request = endpoint_policy.GetEndpointPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_endpoint_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_endpoint_policy( + self, + request: Optional[ + Union[gcn_endpoint_policy.CreateEndpointPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + endpoint_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new EndpointPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.create_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.CreateEndpointPolicyRequest, dict]): + The request object. Request used with the + CreateEndpointPolicy method. + parent (str): + Required. The parent resource of the EndpointPolicy. + Must be in the format ``projects/*/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy (google.cloud.network_services_v1beta1.types.EndpointPolicy): + Required. EndpointPolicy resource to + be created. + + This corresponds to the ``endpoint_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_policy_id (str): + Required. Short name of the + EndpointPolicy resource to be created. + E.g. "CustomECS". + + This corresponds to the ``endpoint_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, endpoint_policy, endpoint_policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_endpoint_policy.CreateEndpointPolicyRequest): + request = gcn_endpoint_policy.CreateEndpointPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if endpoint_policy is not None: + request.endpoint_policy = endpoint_policy + if endpoint_policy_id is not None: + request.endpoint_policy_id = endpoint_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_endpoint_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcn_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_endpoint_policy( + self, + request: Optional[ + Union[gcn_endpoint_policy.UpdateEndpointPolicyRequest, dict] + ] = None, + *, + endpoint_policy: Optional[gcn_endpoint_policy.EndpointPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.update_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.UpdateEndpointPolicyRequest, dict]): + The request object. Request used with the + UpdateEndpointPolicy method. + endpoint_policy (google.cloud.network_services_v1beta1.types.EndpointPolicy): + Required. Updated EndpointPolicy + resource. + + This corresponds to the ``endpoint_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the EndpointPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_services_v1beta1.types.EndpointPolicy` EndpointPolicy is a resource that helps apply desired configuration + on the endpoints that match specific criteria. For + example, this resource can be used to apply + "authentication config" an all endpoints that serve + on port 8080. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [endpoint_policy, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_endpoint_policy.UpdateEndpointPolicyRequest): + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if endpoint_policy is not None: + request.endpoint_policy = endpoint_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_endpoint_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("endpoint_policy.name", request.endpoint_policy.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcn_endpoint_policy.EndpointPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_endpoint_policy( + self, + request: Optional[ + Union[endpoint_policy.DeleteEndpointPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single EndpointPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_services_v1beta1 + + def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_services_v1beta1.types.DeleteEndpointPolicyRequest, dict]): + The request object. Request used with the + DeleteEndpointPolicy method. + name (str): + Required. A name of the EndpointPolicy to delete. Must + be in the format + ``projects/*/locations/global/endpointPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, endpoint_policy.DeleteEndpointPolicyRequest): + request = endpoint_policy.DeleteEndpointPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_endpoint_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "NetworkServicesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("NetworkServicesClient",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/pagers.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/pagers.py new file mode 100644 index 000000000000..9f196848568d --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/pagers.py @@ -0,0 +1,199 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.network_services_v1beta1.types import endpoint_policy + + +class ListEndpointPoliciesPager: + """A pager for iterating through ``list_endpoint_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListEndpointPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``endpoint_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEndpointPolicies`` requests and continue to iterate + through the ``endpoint_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListEndpointPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., endpoint_policy.ListEndpointPoliciesResponse], + request: endpoint_policy.ListEndpointPoliciesRequest, + response: endpoint_policy.ListEndpointPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListEndpointPoliciesRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListEndpointPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = endpoint_policy.ListEndpointPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[endpoint_policy.ListEndpointPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[endpoint_policy.EndpointPolicy]: + for page in self.pages: + yield from page.endpoint_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEndpointPoliciesAsyncPager: + """A pager for iterating through ``list_endpoint_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_services_v1beta1.types.ListEndpointPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``endpoint_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEndpointPolicies`` requests and continue to iterate + through the ``endpoint_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_services_v1beta1.types.ListEndpointPoliciesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[endpoint_policy.ListEndpointPoliciesResponse]], + request: endpoint_policy.ListEndpointPoliciesRequest, + response: endpoint_policy.ListEndpointPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_services_v1beta1.types.ListEndpointPoliciesRequest): + The initial request object. + response (google.cloud.network_services_v1beta1.types.ListEndpointPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = endpoint_policy.ListEndpointPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[endpoint_policy.ListEndpointPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[endpoint_policy.EndpointPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.endpoint_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/README.rst b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/README.rst new file mode 100644 index 000000000000..d42f53f139c5 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``NetworkServicesTransport`` is the ABC for all transports. + +- public child ``NetworkServicesGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``NetworkServicesGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseNetworkServicesRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``NetworkServicesRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/__init__.py new file mode 100644 index 000000000000..27f63fa983d0 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import NetworkServicesTransport +from .grpc import NetworkServicesGrpcTransport +from .grpc_asyncio import NetworkServicesGrpcAsyncIOTransport +from .rest import NetworkServicesRestInterceptor, NetworkServicesRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkServicesTransport]] +_transport_registry["grpc"] = NetworkServicesGrpcTransport +_transport_registry["grpc_asyncio"] = NetworkServicesGrpcAsyncIOTransport +_transport_registry["rest"] = NetworkServicesRestTransport + +__all__ = ( + "NetworkServicesTransport", + "NetworkServicesGrpcTransport", + "NetworkServicesGrpcAsyncIOTransport", + "NetworkServicesRestTransport", + "NetworkServicesRestInterceptor", +) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/base.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/base.py new file mode 100644 index 000000000000..83e3e0798fa0 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/base.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_services_v1beta1 import gapic_version as package_version +from google.cloud.network_services_v1beta1.types import endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NetworkServicesTransport(abc.ABC): + """Abstract transport class for NetworkServices.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "networkservices.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_endpoint_policies: gapic_v1.method.wrap_method( + self.list_endpoint_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_endpoint_policy: gapic_v1.method.wrap_method( + self.get_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_endpoint_policy: gapic_v1.method.wrap_method( + self.create_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_endpoint_policy: gapic_v1.method.wrap_method( + self.update_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_endpoint_policy: gapic_v1.method.wrap_method( + self.delete_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_endpoint_policies( + self, + ) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + Union[ + endpoint_policy.ListEndpointPoliciesResponse, + Awaitable[endpoint_policy.ListEndpointPoliciesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], + Union[ + endpoint_policy.EndpointPolicy, Awaitable[endpoint_policy.EndpointPolicy] + ], + ]: + raise NotImplementedError() + + @property + def create_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("NetworkServicesTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/grpc.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/grpc.py new file mode 100644 index 000000000000..781fe1175241 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/grpc.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.network_services_v1beta1.types import endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +from .base import DEFAULT_CLIENT_INFO, NetworkServicesTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkServicesGrpcTransport(NetworkServicesTransport): + """gRPC backend transport for NetworkServices. + + Service describing handlers for resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_endpoint_policies( + self, + ) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + endpoint_policy.ListEndpointPoliciesResponse, + ]: + r"""Return a callable for the list endpoint policies method over gRPC. + + Lists EndpointPolicies in a given project and + location. + + Returns: + Callable[[~.ListEndpointPoliciesRequest], + ~.ListEndpointPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_endpoint_policies" not in self._stubs: + self._stubs["list_endpoint_policies"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/ListEndpointPolicies", + request_serializer=endpoint_policy.ListEndpointPoliciesRequest.serialize, + response_deserializer=endpoint_policy.ListEndpointPoliciesResponse.deserialize, + ) + return self._stubs["list_endpoint_policies"] + + @property + def get_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], endpoint_policy.EndpointPolicy + ]: + r"""Return a callable for the get endpoint policy method over gRPC. + + Gets details of a single EndpointPolicy. + + Returns: + Callable[[~.GetEndpointPolicyRequest], + ~.EndpointPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_endpoint_policy" not in self._stubs: + self._stubs["get_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/GetEndpointPolicy", + request_serializer=endpoint_policy.GetEndpointPolicyRequest.serialize, + response_deserializer=endpoint_policy.EndpointPolicy.deserialize, + ) + return self._stubs["get_endpoint_policy"] + + @property + def create_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create endpoint policy method over gRPC. + + Creates a new EndpointPolicy in a given project and + location. + + Returns: + Callable[[~.CreateEndpointPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_endpoint_policy" not in self._stubs: + self._stubs["create_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/CreateEndpointPolicy", + request_serializer=gcn_endpoint_policy.CreateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_endpoint_policy"] + + @property + def update_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update endpoint policy method over gRPC. + + Updates the parameters of a single EndpointPolicy. + + Returns: + Callable[[~.UpdateEndpointPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_endpoint_policy" not in self._stubs: + self._stubs["update_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/UpdateEndpointPolicy", + request_serializer=gcn_endpoint_policy.UpdateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_endpoint_policy"] + + @property + def delete_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete endpoint policy method over gRPC. + + Deletes a single EndpointPolicy. + + Returns: + Callable[[~.DeleteEndpointPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_endpoint_policy" not in self._stubs: + self._stubs["delete_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/DeleteEndpointPolicy", + request_serializer=endpoint_policy.DeleteEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_endpoint_policy"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("NetworkServicesGrpcTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/grpc_asyncio.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/grpc_asyncio.py new file mode 100644 index 000000000000..6a918968d73e --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/grpc_asyncio.py @@ -0,0 +1,783 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.network_services_v1beta1.types import endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +from .base import DEFAULT_CLIENT_INFO, NetworkServicesTransport +from .grpc import NetworkServicesGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkServicesGrpcAsyncIOTransport(NetworkServicesTransport): + """gRPC AsyncIO backend transport for NetworkServices. + + Service describing handlers for resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_endpoint_policies( + self, + ) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + Awaitable[endpoint_policy.ListEndpointPoliciesResponse], + ]: + r"""Return a callable for the list endpoint policies method over gRPC. + + Lists EndpointPolicies in a given project and + location. + + Returns: + Callable[[~.ListEndpointPoliciesRequest], + Awaitable[~.ListEndpointPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_endpoint_policies" not in self._stubs: + self._stubs["list_endpoint_policies"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/ListEndpointPolicies", + request_serializer=endpoint_policy.ListEndpointPoliciesRequest.serialize, + response_deserializer=endpoint_policy.ListEndpointPoliciesResponse.deserialize, + ) + return self._stubs["list_endpoint_policies"] + + @property + def get_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], + Awaitable[endpoint_policy.EndpointPolicy], + ]: + r"""Return a callable for the get endpoint policy method over gRPC. + + Gets details of a single EndpointPolicy. + + Returns: + Callable[[~.GetEndpointPolicyRequest], + Awaitable[~.EndpointPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_endpoint_policy" not in self._stubs: + self._stubs["get_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/GetEndpointPolicy", + request_serializer=endpoint_policy.GetEndpointPolicyRequest.serialize, + response_deserializer=endpoint_policy.EndpointPolicy.deserialize, + ) + return self._stubs["get_endpoint_policy"] + + @property + def create_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create endpoint policy method over gRPC. + + Creates a new EndpointPolicy in a given project and + location. + + Returns: + Callable[[~.CreateEndpointPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_endpoint_policy" not in self._stubs: + self._stubs["create_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/CreateEndpointPolicy", + request_serializer=gcn_endpoint_policy.CreateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_endpoint_policy"] + + @property + def update_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update endpoint policy method over gRPC. + + Updates the parameters of a single EndpointPolicy. + + Returns: + Callable[[~.UpdateEndpointPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_endpoint_policy" not in self._stubs: + self._stubs["update_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/UpdateEndpointPolicy", + request_serializer=gcn_endpoint_policy.UpdateEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_endpoint_policy"] + + @property + def delete_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete endpoint policy method over gRPC. + + Deletes a single EndpointPolicy. + + Returns: + Callable[[~.DeleteEndpointPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_endpoint_policy" not in self._stubs: + self._stubs["delete_endpoint_policy"] = self._logged_channel.unary_unary( + "/google.cloud.networkservices.v1beta1.NetworkServices/DeleteEndpointPolicy", + request_serializer=endpoint_policy.DeleteEndpointPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_endpoint_policy"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_endpoint_policies: self._wrap_method( + self.list_endpoint_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_endpoint_policy: self._wrap_method( + self.get_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_endpoint_policy: self._wrap_method( + self.create_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_endpoint_policy: self._wrap_method( + self.update_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_endpoint_policy: self._wrap_method( + self.delete_endpoint_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("NetworkServicesGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/rest.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/rest.py new file mode 100644 index 000000000000..13895bce569b --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/rest.py @@ -0,0 +1,2773 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.network_services_v1beta1._compat import transcode_request +from google.cloud.network_services_v1beta1.types import endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseNetworkServicesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NetworkServicesRestInterceptor: + """Interceptor for NetworkServices. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the NetworkServicesRestTransport. + + .. code-block:: python + class MyCustomNetworkServicesInterceptor(NetworkServicesRestInterceptor): + def pre_create_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_endpoint_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_endpoint_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_endpoint_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_endpoint_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = NetworkServicesRestTransport(interceptor=MyCustomNetworkServicesInterceptor()) + client = NetworkServicesClient(transport=transport) + + + """ + + def pre_create_endpoint_policy( + self, + request: gcn_endpoint_policy.CreateEndpointPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_endpoint_policy.CreateEndpointPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_create_endpoint_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_endpoint_policy + + DEPRECATED. Please use the `post_create_endpoint_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. This `post_create_endpoint_policy` interceptor runs + before the `post_create_endpoint_policy_with_metadata` interceptor. + """ + return response + + def post_create_endpoint_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_endpoint_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkServices server but before it is returned to user code. + + We recommend only using this `post_create_endpoint_policy_with_metadata` + interceptor in new development instead of the `post_create_endpoint_policy` interceptor. + When both interceptors are used, this `post_create_endpoint_policy_with_metadata` interceptor runs after the + `post_create_endpoint_policy` interceptor. The (possibly modified) response returned by + `post_create_endpoint_policy` will be passed to + `post_create_endpoint_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_endpoint_policy( + self, + request: endpoint_policy.DeleteEndpointPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + endpoint_policy.DeleteEndpointPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_endpoint_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_endpoint_policy + + DEPRECATED. Please use the `post_delete_endpoint_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. This `post_delete_endpoint_policy` interceptor runs + before the `post_delete_endpoint_policy_with_metadata` interceptor. + """ + return response + + def post_delete_endpoint_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_endpoint_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkServices server but before it is returned to user code. + + We recommend only using this `post_delete_endpoint_policy_with_metadata` + interceptor in new development instead of the `post_delete_endpoint_policy` interceptor. + When both interceptors are used, this `post_delete_endpoint_policy_with_metadata` interceptor runs after the + `post_delete_endpoint_policy` interceptor. The (possibly modified) response returned by + `post_delete_endpoint_policy` will be passed to + `post_delete_endpoint_policy_with_metadata`. + """ + return response, metadata + + def pre_get_endpoint_policy( + self, + request: endpoint_policy.GetEndpointPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + endpoint_policy.GetEndpointPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_endpoint_policy( + self, response: endpoint_policy.EndpointPolicy + ) -> endpoint_policy.EndpointPolicy: + """Post-rpc interceptor for get_endpoint_policy + + DEPRECATED. Please use the `post_get_endpoint_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. This `post_get_endpoint_policy` interceptor runs + before the `post_get_endpoint_policy_with_metadata` interceptor. + """ + return response + + def post_get_endpoint_policy_with_metadata( + self, + response: endpoint_policy.EndpointPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[endpoint_policy.EndpointPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_endpoint_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkServices server but before it is returned to user code. + + We recommend only using this `post_get_endpoint_policy_with_metadata` + interceptor in new development instead of the `post_get_endpoint_policy` interceptor. + When both interceptors are used, this `post_get_endpoint_policy_with_metadata` interceptor runs after the + `post_get_endpoint_policy` interceptor. The (possibly modified) response returned by + `post_get_endpoint_policy` will be passed to + `post_get_endpoint_policy_with_metadata`. + """ + return response, metadata + + def pre_list_endpoint_policies( + self, + request: endpoint_policy.ListEndpointPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + endpoint_policy.ListEndpointPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_endpoint_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_endpoint_policies( + self, response: endpoint_policy.ListEndpointPoliciesResponse + ) -> endpoint_policy.ListEndpointPoliciesResponse: + """Post-rpc interceptor for list_endpoint_policies + + DEPRECATED. Please use the `post_list_endpoint_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. This `post_list_endpoint_policies` interceptor runs + before the `post_list_endpoint_policies_with_metadata` interceptor. + """ + return response + + def post_list_endpoint_policies_with_metadata( + self, + response: endpoint_policy.ListEndpointPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + endpoint_policy.ListEndpointPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_endpoint_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkServices server but before it is returned to user code. + + We recommend only using this `post_list_endpoint_policies_with_metadata` + interceptor in new development instead of the `post_list_endpoint_policies` interceptor. + When both interceptors are used, this `post_list_endpoint_policies_with_metadata` interceptor runs after the + `post_list_endpoint_policies` interceptor. The (possibly modified) response returned by + `post_list_endpoint_policies` will be passed to + `post_list_endpoint_policies_with_metadata`. + """ + return response, metadata + + def pre_update_endpoint_policy( + self, + request: gcn_endpoint_policy.UpdateEndpointPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_endpoint_policy.UpdateEndpointPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_endpoint_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_update_endpoint_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_endpoint_policy + + DEPRECATED. Please use the `post_update_endpoint_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. This `post_update_endpoint_policy` interceptor runs + before the `post_update_endpoint_policy_with_metadata` interceptor. + """ + return response + + def post_update_endpoint_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_endpoint_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkServices server but before it is returned to user code. + + We recommend only using this `post_update_endpoint_policy_with_metadata` + interceptor in new development instead of the `post_update_endpoint_policy` interceptor. + When both interceptors are used, this `post_update_endpoint_policy_with_metadata` interceptor runs after the + `post_update_endpoint_policy` interceptor. The (possibly modified) response returned by + `post_update_endpoint_policy` will be passed to + `post_update_endpoint_policy_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkServices server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the NetworkServices server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class NetworkServicesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: NetworkServicesRestInterceptor + + +class NetworkServicesRestTransport(_BaseNetworkServicesRestTransport): + """REST backend synchronous transport for NetworkServices. + + Service describing handlers for resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[NetworkServicesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[NetworkServicesRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or NetworkServicesRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateEndpointPolicy( + _BaseNetworkServicesRestTransport._BaseCreateEndpointPolicy, + NetworkServicesRestStub, + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.CreateEndpointPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcn_endpoint_policy.CreateEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create endpoint policy method over HTTP. + + Args: + request (~.gcn_endpoint_policy.CreateEndpointPolicyRequest): + The request object. Request used with the + CreateEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkServicesRestTransport._BaseCreateEndpointPolicy._get_http_options() + request, metadata = self._interceptor.pre_create_endpoint_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseCreateEndpointPolicy, + "_BaseCreateEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.CreateEndpointPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "CreateEndpointPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._CreateEndpointPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_endpoint_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_endpoint_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesClient.create_endpoint_policy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "CreateEndpointPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteEndpointPolicy( + _BaseNetworkServicesRestTransport._BaseDeleteEndpointPolicy, + NetworkServicesRestStub, + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.DeleteEndpointPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: endpoint_policy.DeleteEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete endpoint policy method over HTTP. + + Args: + request (~.endpoint_policy.DeleteEndpointPolicyRequest): + The request object. Request used with the + DeleteEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkServicesRestTransport._BaseDeleteEndpointPolicy._get_http_options() + request, metadata = self._interceptor.pre_delete_endpoint_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseDeleteEndpointPolicy, + "_BaseDeleteEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.DeleteEndpointPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "DeleteEndpointPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._DeleteEndpointPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_endpoint_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_endpoint_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesClient.delete_endpoint_policy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "DeleteEndpointPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEndpointPolicy( + _BaseNetworkServicesRestTransport._BaseGetEndpointPolicy, + NetworkServicesRestStub, + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.GetEndpointPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: endpoint_policy.GetEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> endpoint_policy.EndpointPolicy: + r"""Call the get endpoint policy method over HTTP. + + Args: + request (~.endpoint_policy.GetEndpointPolicyRequest): + The request object. Request used with the + GetEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.endpoint_policy.EndpointPolicy: + EndpointPolicy is a resource that + helps apply desired configuration on the + endpoints that match specific criteria. + For example, this resource can be used + to apply "authentication config" an all + endpoints that serve on port 8080. + + """ + + http_options = _BaseNetworkServicesRestTransport._BaseGetEndpointPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_endpoint_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseGetEndpointPolicy, + "_BaseGetEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.GetEndpointPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetEndpointPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._GetEndpointPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = endpoint_policy.EndpointPolicy() + pb_resp = endpoint_policy.EndpointPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_endpoint_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_endpoint_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = endpoint_policy.EndpointPolicy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesClient.get_endpoint_policy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetEndpointPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEndpointPolicies( + _BaseNetworkServicesRestTransport._BaseListEndpointPolicies, + NetworkServicesRestStub, + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.ListEndpointPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: endpoint_policy.ListEndpointPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> endpoint_policy.ListEndpointPoliciesResponse: + r"""Call the list endpoint policies method over HTTP. + + Args: + request (~.endpoint_policy.ListEndpointPoliciesRequest): + The request object. Request used with the + ListEndpointPolicies method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.endpoint_policy.ListEndpointPoliciesResponse: + Response returned by the + ListEndpointPolicies method. + + """ + + http_options = _BaseNetworkServicesRestTransport._BaseListEndpointPolicies._get_http_options() + request, metadata = self._interceptor.pre_list_endpoint_policies( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseListEndpointPolicies, + "_BaseListEndpointPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.ListEndpointPolicies", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "ListEndpointPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._ListEndpointPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = endpoint_policy.ListEndpointPoliciesResponse() + pb_resp = endpoint_policy.ListEndpointPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_endpoint_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_endpoint_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + endpoint_policy.ListEndpointPoliciesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesClient.list_endpoint_policies", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "ListEndpointPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEndpointPolicy( + _BaseNetworkServicesRestTransport._BaseUpdateEndpointPolicy, + NetworkServicesRestStub, + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.UpdateEndpointPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcn_endpoint_policy.UpdateEndpointPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update endpoint policy method over HTTP. + + Args: + request (~.gcn_endpoint_policy.UpdateEndpointPolicyRequest): + The request object. Request used with the + UpdateEndpointPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkServicesRestTransport._BaseUpdateEndpointPolicy._get_http_options() + request, metadata = self._interceptor.pre_update_endpoint_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseUpdateEndpointPolicy, + "_BaseUpdateEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.UpdateEndpointPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "UpdateEndpointPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._UpdateEndpointPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_endpoint_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_endpoint_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesClient.update_endpoint_policy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "UpdateEndpointPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.CreateEndpointPolicyRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.DeleteEndpointPolicyRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_endpoint_policy( + self, + ) -> Callable[ + [endpoint_policy.GetEndpointPolicyRequest], endpoint_policy.EndpointPolicy + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_endpoint_policies( + self, + ) -> Callable[ + [endpoint_policy.ListEndpointPoliciesRequest], + endpoint_policy.ListEndpointPoliciesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEndpointPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_endpoint_policy( + self, + ) -> Callable[ + [gcn_endpoint_policy.UpdateEndpointPolicyRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEndpointPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseNetworkServicesRestTransport._BaseGetLocation, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseNetworkServicesRestTransport._BaseGetLocation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.GetLocation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseNetworkServicesRestTransport._BaseListLocations, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseNetworkServicesRestTransport._BaseListLocations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.ListLocations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseNetworkServicesRestTransport._BaseGetIamPolicy, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseNetworkServicesRestTransport._BaseGetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseNetworkServicesRestTransport._BaseSetIamPolicy, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseNetworkServicesRestTransport._BaseSetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseNetworkServicesRestTransport._BaseTestIamPermissions, + NetworkServicesRestStub, + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseNetworkServicesRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseTestIamPermissions, + "_BaseTestIamPermissions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseNetworkServicesRestTransport._BaseCancelOperation, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseNetworkServicesRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.CancelOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseNetworkServicesRestTransport._BaseDeleteOperation, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseNetworkServicesRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseDeleteOperation, + "_BaseDeleteOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseNetworkServicesRestTransport._BaseGetOperation, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseNetworkServicesRestTransport._BaseGetOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.GetOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseNetworkServicesRestTransport._BaseListOperations, NetworkServicesRestStub + ): + def __hash__(self): + return hash("NetworkServicesRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseNetworkServicesRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseNetworkServicesRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networkservices_v1beta1.NetworkServicesClient.ListOperations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServicesRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networkservices_v1beta1.NetworkServicesAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.networkservices.v1beta1.NetworkServices", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("NetworkServicesRestTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/rest_base.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/rest_base.py new file mode 100644 index 000000000000..8306886cd7e4 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/services/network_services/transports/rest_base.py @@ -0,0 +1,313 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.network_services_v1beta1.types import endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +from .base import DEFAULT_CLIENT_INFO, NetworkServicesTransport + + +class _BaseNetworkServicesRestTransport(NetworkServicesTransport): + """Base REST backend transport for NetworkServices. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "networkservices.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'networkservices.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateEndpointPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "endpointPolicyId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/endpointPolicies", + "body": "endpoint_policy", + }, + ] + return http_options + + class _BaseDeleteEndpointPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/endpointPolicies/*}", + }, + ] + return http_options + + class _BaseGetEndpointPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/endpointPolicies/*}", + }, + ] + return http_options + + class _BaseListEndpointPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/endpointPolicies", + }, + ] + return http_options + + class _BaseUpdateEndpointPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}", + "body": "endpoint_policy", + }, + ] + return http_options + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}", + }, + ] + return http_options + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*}/locations", + }, + ] + return http_options + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/locations/*/endpointPolicies/*}:getIamPolicy", + }, + ] + return http_options + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/endpointPolicies/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/locations/*/endpointPolicies/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseNetworkServicesRestTransport",) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/__init__.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/__init__.py new file mode 100644 index 000000000000..7a8d67c964ec --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/__init__.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .common import ( + EndpointMatcher, + OperationMetadata, + TrafficPortSelector, +) +from .dep import ( + CreateExtensionBindingRequest, + CreateLbRouteExtensionRequest, + CreateLbTrafficExtensionRequest, + DeleteExtensionBindingRequest, + DeleteLbRouteExtensionRequest, + DeleteLbTrafficExtensionRequest, + EventType, + ExtensionBinding, + ExtensionChain, + GetExtensionBindingRequest, + GetLbRouteExtensionRequest, + GetLbTrafficExtensionRequest, + LbRouteExtension, + LbTrafficExtension, + ListExtensionBindingsRequest, + ListExtensionBindingsResponse, + ListLbRouteExtensionsRequest, + ListLbRouteExtensionsResponse, + ListLbTrafficExtensionsRequest, + ListLbTrafficExtensionsResponse, + LoadBalancingScheme, + UpdateExtensionBindingRequest, + UpdateLbRouteExtensionRequest, + UpdateLbTrafficExtensionRequest, +) +from .endpoint_policy import ( + CreateEndpointPolicyRequest, + DeleteEndpointPolicyRequest, + EndpointPolicy, + GetEndpointPolicyRequest, + ListEndpointPoliciesRequest, + ListEndpointPoliciesResponse, + UpdateEndpointPolicyRequest, +) + +__all__ = ( + "EndpointMatcher", + "OperationMetadata", + "TrafficPortSelector", + "CreateExtensionBindingRequest", + "CreateLbRouteExtensionRequest", + "CreateLbTrafficExtensionRequest", + "DeleteExtensionBindingRequest", + "DeleteLbRouteExtensionRequest", + "DeleteLbTrafficExtensionRequest", + "ExtensionBinding", + "ExtensionChain", + "GetExtensionBindingRequest", + "GetLbRouteExtensionRequest", + "GetLbTrafficExtensionRequest", + "LbRouteExtension", + "LbTrafficExtension", + "ListExtensionBindingsRequest", + "ListExtensionBindingsResponse", + "ListLbRouteExtensionsRequest", + "ListLbRouteExtensionsResponse", + "ListLbTrafficExtensionsRequest", + "ListLbTrafficExtensionsResponse", + "UpdateExtensionBindingRequest", + "UpdateLbRouteExtensionRequest", + "UpdateLbTrafficExtensionRequest", + "EventType", + "LoadBalancingScheme", + "CreateEndpointPolicyRequest", + "DeleteEndpointPolicyRequest", + "EndpointPolicy", + "GetEndpointPolicyRequest", + "ListEndpointPoliciesRequest", + "ListEndpointPoliciesResponse", + "UpdateEndpointPolicyRequest", +) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/common.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/common.py new file mode 100644 index 000000000000..03671060b424 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/common.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.networkservices.v1beta1", + manifest={ + "OperationMetadata", + "TrafficPortSelector", + "EndpointMatcher", + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +class TrafficPortSelector(proto.Message): + r"""Specification of a port-based selector. + + Attributes: + ports (MutableSequence[str]): + Optional. A list of ports. Can be port numbers or port range + (example, [80-90] specifies all ports from 80 to 90, + including 80 and 90) or named ports or \* to specify all + ports. If the list is empty, all ports are selected. + """ + + ports: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class EndpointMatcher(proto.Message): + r"""A definition of a matcher that selects endpoints to which the + policies should be applied. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + metadata_label_matcher (google.cloud.network_services_v1beta1.types.EndpointMatcher.MetadataLabelMatcher): + The matcher is based on node metadata + presented by xDS clients. + + This field is a member of `oneof`_ ``matcher_type``. + """ + + class MetadataLabelMatcher(proto.Message): + r"""The matcher that is based on node metadata presented by xDS + clients. + + Attributes: + metadata_label_match_criteria (google.cloud.network_services_v1beta1.types.EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria): + Specifies how matching should be done. + + Supported values are: MATCH_ANY: At least one of the Labels + specified in the matcher should match the metadata presented + by xDS client. MATCH_ALL: The metadata presented by the xDS + client should contain all of the labels specified here. + + The selection is determined based on the best match. For + example, suppose there are three EndpointPolicy resources + P1, P2 and P3 and if P1 has a the matcher as MATCH_ANY , P2 has MATCH_ALL , and P3 has MATCH_ALL + . + + If a client with label connects, the config from P1 + will be selected. + + If a client with label connects, the config from + P2 will be selected. + + If a client with label connects, the config + from P3 will be selected. + + If there is more than one best match, (for example, if a + config P4 with selector exists and if a client + with label connects), an error will be thrown. + metadata_labels (MutableSequence[google.cloud.network_services_v1beta1.types.EndpointMatcher.MetadataLabelMatcher.MetadataLabels]): + The list of label value pairs that must match labels in the + provided metadata based on filterMatchCriteria This list can + have at most 64 entries. The list can be empty if the match + criteria is MATCH_ANY, to specify a wildcard match (i.e this + matches any client). + """ + + class MetadataLabelMatchCriteria(proto.Enum): + r"""Possible criteria values that define logic of how matching is + made. + + Values: + METADATA_LABEL_MATCH_CRITERIA_UNSPECIFIED (0): + Default value. Should not be used. + MATCH_ANY (1): + At least one of the Labels specified in the + matcher should match the metadata presented by + xDS client. + MATCH_ALL (2): + The metadata presented by the xDS client + should contain all of the labels specified here. + """ + + METADATA_LABEL_MATCH_CRITERIA_UNSPECIFIED = 0 + MATCH_ANY = 1 + MATCH_ALL = 2 + + class MetadataLabels(proto.Message): + r"""Defines a name-pair value for a single label. + + Attributes: + label_name (str): + Required. Label name presented as key in xDS + Node Metadata. + label_value (str): + Required. Label value presented as value + corresponding to the above key, in xDS Node + Metadata. + """ + + label_name: str = proto.Field( + proto.STRING, + number=1, + ) + label_value: str = proto.Field( + proto.STRING, + number=2, + ) + + metadata_label_match_criteria: "EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria" = proto.Field( + proto.ENUM, + number=1, + enum="EndpointMatcher.MetadataLabelMatcher.MetadataLabelMatchCriteria", + ) + metadata_labels: MutableSequence[ + "EndpointMatcher.MetadataLabelMatcher.MetadataLabels" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="EndpointMatcher.MetadataLabelMatcher.MetadataLabels", + ) + + metadata_label_matcher: MetadataLabelMatcher = proto.Field( + proto.MESSAGE, + number=1, + oneof="matcher_type", + message=MetadataLabelMatcher, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/dep.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/dep.py new file mode 100644 index 000000000000..afdf05efd359 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/dep.py @@ -0,0 +1,1510 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.networkservices.v1beta1", + manifest={ + "EventType", + "LoadBalancingScheme", + "ExtensionChain", + "LbTrafficExtension", + "ListLbTrafficExtensionsRequest", + "ListLbTrafficExtensionsResponse", + "GetLbTrafficExtensionRequest", + "CreateLbTrafficExtensionRequest", + "UpdateLbTrafficExtensionRequest", + "DeleteLbTrafficExtensionRequest", + "LbRouteExtension", + "ListLbRouteExtensionsRequest", + "ListLbRouteExtensionsResponse", + "GetLbRouteExtensionRequest", + "CreateLbRouteExtensionRequest", + "UpdateLbRouteExtensionRequest", + "DeleteLbRouteExtensionRequest", + "ExtensionBinding", + "ListExtensionBindingsRequest", + "ListExtensionBindingsResponse", + "GetExtensionBindingRequest", + "CreateExtensionBindingRequest", + "UpdateExtensionBindingRequest", + "DeleteExtensionBindingRequest", + }, +) + + +class EventType(proto.Enum): + r"""The part of the request or response for which the extension + is called. + + Values: + EVENT_TYPE_UNSPECIFIED (0): + Unspecified value. Do not use. + REQUEST_HEADERS (1): + If included in ``supported_events``, the extension is called + when the HTTP request headers arrive. + REQUEST_BODY (2): + If included in ``supported_events``, the extension is called + when the HTTP request body arrives. + RESPONSE_HEADERS (3): + If included in ``supported_events``, the extension is called + when the HTTP response headers arrive. + RESPONSE_BODY (4): + If included in ``supported_events``, the extension is called + when the HTTP response body arrives. + REQUEST_TRAILERS (5): + If included in ``supported_events``, the extension is called + when the HTTP request trailers arrives. + RESPONSE_TRAILERS (6): + If included in ``supported_events``, the extension is called + when the HTTP response trailers arrives. + """ + + EVENT_TYPE_UNSPECIFIED = 0 + REQUEST_HEADERS = 1 + REQUEST_BODY = 2 + RESPONSE_HEADERS = 3 + RESPONSE_BODY = 4 + REQUEST_TRAILERS = 5 + RESPONSE_TRAILERS = 6 + + +class LoadBalancingScheme(proto.Enum): + r"""Load balancing schemes supported by the ``LbTrafficExtension`` + resource and ``LbRouteExtension`` resource. For more information, + refer to `Choosing a load + balancer `__. + + Values: + LOAD_BALANCING_SCHEME_UNSPECIFIED (0): + Default value. Do not use. + INTERNAL_MANAGED (1): + Signifies that this is used for Internal + HTTP(S) Load Balancing. + EXTERNAL_MANAGED (2): + Signifies that this is used for External + Managed HTTP(S) Load Balancing. + """ + + LOAD_BALANCING_SCHEME_UNSPECIFIED = 0 + INTERNAL_MANAGED = 1 + EXTERNAL_MANAGED = 2 + + +class ExtensionChain(proto.Message): + r"""A single extension chain wrapper that contains the match + conditions and extensions to execute. + + Attributes: + name (str): + Required. The name for this extension chain. + The name is logged as part of the HTTP request + logs. The name must conform with RFC-1034, is + restricted to lower-cased letters, numbers and + hyphens, and can have a maximum length of 63 + characters. Additionally, the first character + must be a letter and the last a letter or a + number. + match_condition (google.cloud.network_services_v1beta1.types.ExtensionChain.MatchCondition): + Required. Conditions under which this chain + is invoked for a request. + extensions (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionChain.Extension]): + Required. A set of extensions to execute for the matching + request. At least one extension is required. Up to 3 + extensions can be defined for each extension chain for + ``LbTrafficExtension`` resource. ``LbRouteExtension`` chains + are limited to 1 extension per extension chain. + """ + + class MatchCondition(proto.Message): + r"""Conditions under which this chain is invoked for a request. + + Attributes: + cel_expression (str): + Required. A Common Expression Language (CEL) expression that + is used to match requests for which the extension chain is + executed. + + For more information, see `CEL matcher language + reference `__. + """ + + cel_expression: str = proto.Field( + proto.STRING, + number=1, + ) + + class Extension(proto.Message): + r"""A single extension in the chain to execute for the matching + request. + + Attributes: + name (str): + Required. The name for this extension. + The name is logged as part of the HTTP request + logs. The name must conform with RFC-1034, is + restricted to lower-cased letters, numbers and + hyphens, and can have a maximum length of 63 + characters. Additionally, the first character + must be a letter and the last a letter or a + number. + authority (str): + Optional. The ``:authority`` header in the gRPC request sent + from Envoy to the extension service. Required for Callout + extensions. + service (str): + Required. The reference to the service that runs the + extension. + + Currently only callout extensions are supported here. + + To configure a callout extension, ``service`` must be a + fully-qualified reference to a `backend + service `__ + in the format: + ``https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/backendServices/{backendService}`` + or + ``https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}``. + supported_events (MutableSequence[google.cloud.network_services_v1beta1.types.EventType]): + Optional. A set of events during request or response + processing for which this extension is called. This field is + required for the ``LbTrafficExtension`` resource. It's not + relevant for the ``LbRouteExtension`` resource. + timeout (google.protobuf.duration_pb2.Duration): + Optional. Specifies the timeout for each + individual message on the stream. The timeout + must be between 10-1000 milliseconds. Required + for Callout extensions. + fail_open (bool): + Optional. Determines how the proxy behaves if the call to + the extension fails or times out. + + When set to ``TRUE``, request or response processing + continues without error. Any subsequent extensions in the + extension chain are also executed. When set to ``FALSE`` or + the default setting of ``FALSE`` is used, one of the + following happens: + + - If response headers have not been delivered to the + downstream client, a generic 500 error is returned to the + client. The error response can be tailored by configuring + a custom error response in the load balancer. + + - If response headers have been delivered, then the HTTP + stream to the downstream client is reset. + forward_headers (MutableSequence[str]): + Optional. List of the HTTP headers to forward + to the extension (from the client or backend). + If omitted, all headers are sent. Each element + is a string indicating the header name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + authority: str = proto.Field( + proto.STRING, + number=2, + ) + service: str = proto.Field( + proto.STRING, + number=3, + ) + supported_events: MutableSequence["EventType"] = proto.RepeatedField( + proto.ENUM, + number=4, + enum="EventType", + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + fail_open: bool = proto.Field( + proto.BOOL, + number=6, + ) + forward_headers: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + match_condition: MatchCondition = proto.Field( + proto.MESSAGE, + number=2, + message=MatchCondition, + ) + extensions: MutableSequence[Extension] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Extension, + ) + + +class LbTrafficExtension(proto.Message): + r"""``LbTrafficExtension`` is a resource that lets the extension service + modify the headers and payloads of both requests and responses + without impacting the choice of backend services or any other + security policies associated with the backend service. + + Attributes: + name (str): + Required. Identifier. Name of the ``LbTrafficExtension`` + resource in the following format: + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + description (str): + Optional. A human-readable description of the + resource. + labels (MutableMapping[str, str]): + Optional. Set of labels associated with the + ``LbTrafficExtension`` resource. + + The format must comply with `the requirements for + labels `__ + for Google Cloud resources. + forwarding_rules (MutableSequence[str]): + Required. A list of references to the forwarding rules to + which this service extension is attached to. At least one + forwarding rule is required. There can be only one + ``LBTrafficExtension`` resource per forwarding rule. + extension_chains (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionChain]): + Required. A set of ordered extension chains + that contain the match conditions and extensions + to execute. Match conditions for each extension + chain are evaluated in sequence for a given + request. The first extension chain that has a + condition that matches the request is executed. + Any subsequent extension chains do not execute. + Limited to 5 extension chains per resource. + load_balancing_scheme (google.cloud.network_services_v1beta1.types.LoadBalancingScheme): + Required. All backend services and forwarding rules + referenced by this extension must share the same load + balancing scheme. Supported values: ``INTERNAL_MANAGED``, + ``EXTERNAL_MANAGED``. For more information, refer to + `Choosing a load + balancer `__. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + forwarding_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + extension_chains: MutableSequence["ExtensionChain"] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="ExtensionChain", + ) + load_balancing_scheme: "LoadBalancingScheme" = proto.Field( + proto.ENUM, + number=8, + enum="LoadBalancingScheme", + ) + + +class ListLbTrafficExtensionsRequest(proto.Message): + r"""Message for requesting list of ``LbTrafficExtension`` resources. + + Attributes: + parent (str): + Required. The project and location from which the + ``LbTrafficExtension`` resources are listed, specified in + the following format: + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. Requested page size. The server + might return fewer items than requested. If + unspecified, the server picks an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results that the server returns. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListLbTrafficExtensionsResponse(proto.Message): + r"""Message for response to listing ``LbTrafficExtension`` resources. + + Attributes: + lb_traffic_extensions (MutableSequence[google.cloud.network_services_v1beta1.types.LbTrafficExtension]): + The list of ``LbTrafficExtension`` resources. + next_page_token (str): + A token identifying a page of results that + the server returns. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + lb_traffic_extensions: MutableSequence["LbTrafficExtension"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LbTrafficExtension", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetLbTrafficExtensionRequest(proto.Message): + r"""Message for getting a ``LbTrafficExtension`` resource. + + Attributes: + name (str): + Required. A name of the ``LbTrafficExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateLbTrafficExtensionRequest(proto.Message): + r"""Message for creating a ``LbTrafficExtension`` resource. + + Attributes: + parent (str): + Required. The parent resource of the ``LbTrafficExtension`` + resource. Must be in the format + ``projects/{project}/locations/{location}``. + lb_traffic_extension_id (str): + Required. User-provided ID of the ``LbTrafficExtension`` + resource to be created. + lb_traffic_extension (google.cloud.network_services_v1beta1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` resource to be created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, ignores the second request. This prevents + clients from accidentally creating duplicate + commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + lb_traffic_extension_id: str = proto.Field( + proto.STRING, + number=2, + ) + lb_traffic_extension: "LbTrafficExtension" = proto.Field( + proto.MESSAGE, + number=3, + message="LbTrafficExtension", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateLbTrafficExtensionRequest(proto.Message): + r"""Message for updating a ``LbTrafficExtension`` resource. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Used to specify the fields to be overwritten in + the ``LbTrafficExtension`` resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field is overwritten if it + is in the mask. If the user does not specify a mask, then + all fields are overwritten. + lb_traffic_extension (google.cloud.network_services_v1beta1.types.LbTrafficExtension): + Required. ``LbTrafficExtension`` resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, ignores the second request. This prevents + clients from accidentally creating duplicate + commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + lb_traffic_extension: "LbTrafficExtension" = proto.Field( + proto.MESSAGE, + number=2, + message="LbTrafficExtension", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteLbTrafficExtensionRequest(proto.Message): + r"""Message for deleting a ``LbTrafficExtension`` resource. + + Attributes: + name (str): + Required. The name of the ``LbTrafficExtension`` resource to + delete. Must be in the format + ``projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}``. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, ignores the second request. This prevents + clients from accidentally creating duplicate + commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LbRouteExtension(proto.Message): + r"""``LbRouteExtension`` is a resource that lets you control where + traffic is routed to for a given request. + + Attributes: + name (str): + Required. Identifier. Name of the ``LbRouteExtension`` + resource in the following format: + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + description (str): + Optional. A human-readable description of the + resource. + labels (MutableMapping[str, str]): + Optional. Set of labels associated with the + ``LbRouteExtension`` resource. + + The format must comply with `the requirements for + labels `__ + for Google Cloud resources. + forwarding_rules (MutableSequence[str]): + Required. A list of references to the forwarding rules to + which this service extension is attached to. At least one + forwarding rule is required. There can be only one + ``LbRouteExtension`` resource per forwarding rule. + extension_chains (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionChain]): + Required. A set of ordered extension chains + that contain the match conditions and extensions + to execute. Match conditions for each extension + chain are evaluated in sequence for a given + request. The first extension chain that has a + condition that matches the request is executed. + Any subsequent extension chains do not execute. + Limited to 5 extension chains per resource. + load_balancing_scheme (google.cloud.network_services_v1beta1.types.LoadBalancingScheme): + Required. All backend services and forwarding rules + referenced by this extension must share the same load + balancing scheme. Supported values: ``INTERNAL_MANAGED``, + ``EXTERNAL_MANAGED``. For more information, refer to + `Choosing a load + balancer `__. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + forwarding_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + extension_chains: MutableSequence["ExtensionChain"] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="ExtensionChain", + ) + load_balancing_scheme: "LoadBalancingScheme" = proto.Field( + proto.ENUM, + number=8, + enum="LoadBalancingScheme", + ) + + +class ListLbRouteExtensionsRequest(proto.Message): + r"""Message for requesting list of ``LbRouteExtension`` resources. + + Attributes: + parent (str): + Required. The project and location from which the + ``LbRouteExtension`` resources are listed, specified in the + following format: + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. Requested page size. The server + might return fewer items than requested. If + unspecified, the server picks an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results that the server returns. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListLbRouteExtensionsResponse(proto.Message): + r"""Message for response to listing ``LbRouteExtension`` resources. + + Attributes: + lb_route_extensions (MutableSequence[google.cloud.network_services_v1beta1.types.LbRouteExtension]): + The list of ``LbRouteExtension`` resources. + next_page_token (str): + A token identifying a page of results that + the server returns. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + lb_route_extensions: MutableSequence["LbRouteExtension"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LbRouteExtension", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetLbRouteExtensionRequest(proto.Message): + r"""Message for getting a ``LbRouteExtension`` resource. + + Attributes: + name (str): + Required. A name of the ``LbRouteExtension`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateLbRouteExtensionRequest(proto.Message): + r"""Message for creating a ``LbRouteExtension`` resource. + + Attributes: + parent (str): + Required. The parent resource of the ``LbRouteExtension`` + resource. Must be in the format + ``projects/{project}/locations/{location}``. + lb_route_extension_id (str): + Required. User-provided ID of the ``LbRouteExtension`` + resource to be created. + lb_route_extension (google.cloud.network_services_v1beta1.types.LbRouteExtension): + Required. ``LbRouteExtension`` resource to be created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, ignores the second request. This prevents + clients from accidentally creating duplicate + commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + lb_route_extension_id: str = proto.Field( + proto.STRING, + number=2, + ) + lb_route_extension: "LbRouteExtension" = proto.Field( + proto.MESSAGE, + number=3, + message="LbRouteExtension", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateLbRouteExtensionRequest(proto.Message): + r"""Message for updating a ``LbRouteExtension`` resource. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Used to specify the fields to be overwritten in + the ``LbRouteExtension`` resource by the update. The fields + specified in the update_mask are relative to the resource, + not the full request. A field is overwritten if it is in the + mask. If the user does not specify a mask, then all fields + are overwritten. + lb_route_extension (google.cloud.network_services_v1beta1.types.LbRouteExtension): + Required. ``LbRouteExtension`` resource being updated. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, ignores the second request. This prevents + clients from accidentally creating duplicate + commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + lb_route_extension: "LbRouteExtension" = proto.Field( + proto.MESSAGE, + number=2, + message="LbRouteExtension", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteLbRouteExtensionRequest(proto.Message): + r"""Message for deleting a ``LbRouteExtension`` resource. + + Attributes: + name (str): + Required. The name of the ``LbRouteExtension`` resource to + delete. Must be in the format + ``projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}``. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server can + ignore the request if it has already been + completed. The server guarantees that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, ignores the second request. This prevents + clients from accidentally creating duplicate + commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ExtensionBinding(proto.Message): + r"""``ExtensionBinding`` is a resource representing the attachment of an + extension to a service. + + Attributes: + name (str): + Identifier. Name of the ``ExtensionBinding`` resource in the + following format: + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + description (str): + Optional. A human-readable description of the + resource. + labels (MutableMapping[str, str]): + Optional. Set of labels associated with the + ``ExtensionBinding`` resource. + + The format must comply with `the following + requirements `__. + etag (str): + Optional. Etag of the resource. + If provided, it must match the server's etag. If + the provided etag does not match the server's + etag, the request will fail with a 409 ABORTED + error. + producer_extension (str): + Required. The name of the extension that this binding should + attach to target resources. + + Format: For Google-provided extensions, specify the service + endpoint (see `Model Armor + integration `__) + target (google.cloud.network_services_v1beta1.types.ExtensionBinding.Target): + Required. Specifies a target to which this + ``ExtensionBinding`` should be attached. The target can be + either a single resource or a scope of resources. + match_conditions (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition]): + Optional. A list of match conditions to match + against the incoming request. The extension will + be invoked if at least one condition matches the + request, or if no match conditions are + specified. Limited to 5 conditions. + fail_open (bool): + Optional. Determines the behavior of the extension binding + when the call to the extension fails or times out. Default + value is ``FALSE``. + + When set to ``TRUE``, failures of the extension are silently + ignored. + producer_metadata (MutableMapping[str, str]): + Optional. Additional metadata that should be + passed to the attached extension with each + request. + priority (int): + Optional. Priority of the extension binding. + Lower numbers indicate higher priority. Priority + of extension bindings are used to determine the + order in which extension bindings are applied to + a request. + """ + + class Target(proto.Message): + r"""Specifies a list of targets to which this ``ExtensionBinding`` + should attach. + + Attributes: + resources (MutableSequence[str]): + Optional. The reference to the target resource, to which + this binding should attach. Exactly one of ``resources`` or + ``scope`` must be set. + scope (google.cloud.network_services_v1beta1.types.ExtensionBinding.Target.Scope): + Optional. Specifies the scope of resources to which this + binding should attach. Exactly one of ``resources`` or + ``scope`` must be set. + """ + + class Scope(proto.Message): + r"""Specifies the scope of resources to which this binding should + attach. + + Attributes: + parent (str): + Required. Parent resource name specification, in the format: + ``projects/{project_number}``. + resource_types (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionBinding.Target.Scope.ResourceType]): + Required. Type of the resource to which the + binding should attach. Limited to 1 resource + type. + """ + + class ResourceType(proto.Enum): + r"""Resource types that should be targeted by the binding. + + Values: + RESOURCE_TYPE_UNSPECIFIED (0): + Default value. Should not be used. + AI_APPLICATION (1): + AI Application resources. + AGENT_GATEWAY (2): + Agent Gateway resources. + """ + + RESOURCE_TYPE_UNSPECIFIED = 0 + AI_APPLICATION = 1 + AGENT_GATEWAY = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_types: MutableSequence[ + "ExtensionBinding.Target.Scope.ResourceType" + ] = proto.RepeatedField( + proto.ENUM, + number=2, + enum="ExtensionBinding.Target.Scope.ResourceType", + ) + + resources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + scope: "ExtensionBinding.Target.Scope" = proto.Field( + proto.MESSAGE, + number=2, + message="ExtensionBinding.Target.Scope", + ) + + class MatchCondition(proto.Message): + r"""Conditions to match against the incoming request. + + Attributes: + to (google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.To): + Optional. Describes properties of a + destination of a request. If specified, the + extension will only be invoked on requests to + destinations that match the specified criteria. + """ + + class StringMatch(proto.Message): + r"""Specifies matching logic for string values. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + exact (str): + Optional. The input string must match exactly the string + specified here. + + Examples: + + - ``abc`` only matches the value ``abc``. + + This field is a member of `oneof`_ ``match_pattern``. + prefix (str): + Optional. The input string must have the prefix specified + here. Note: empty prefix is not allowed. + + Examples: + + - ``abc`` matches the value ``abc.xyz`` + + This field is a member of `oneof`_ ``match_pattern``. + suffix (str): + Optional. The input string must have the suffix specified + here. Note: empty prefix is not allowed, please use regex + instead. + + Examples: + + - ``abc`` matches the value ``xyz.abc`` + + This field is a member of `oneof`_ ``match_pattern``. + contains (str): + Optional. The input string must have the substring specified + here. Note: empty contains match is not allowed, please use + regex instead. + + Examples: + + - ``abc`` matches the value ``xyz.abc.def`` + + This field is a member of `oneof`_ ``match_pattern``. + ignore_case (bool): + Optional. If true, indicates the + exact/prefix/suffix/contains matching should be case + insensitive. For example, the matcher ``data`` will match + both input string ``Data`` and ``data`` if set to true. + """ + + exact: str = proto.Field( + proto.STRING, + number=1, + oneof="match_pattern", + ) + prefix: str = proto.Field( + proto.STRING, + number=2, + oneof="match_pattern", + ) + suffix: str = proto.Field( + proto.STRING, + number=3, + oneof="match_pattern", + ) + contains: str = proto.Field( + proto.STRING, + number=4, + oneof="match_pattern", + ) + ignore_case: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class HeaderMatch(proto.Message): + r"""Determines how an HTTP header should be matched. + + Attributes: + name (str): + Required. Specifies the name of the header in + the request. + value (google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.StringMatch): + Optional. Specifies how the header match will + be performed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: "ExtensionBinding.MatchCondition.StringMatch" = proto.Field( + proto.MESSAGE, + number=2, + message="ExtensionBinding.MatchCondition.StringMatch", + ) + + class To(proto.Message): + r"""Describes properties of one or more destinations of a + request. + + Attributes: + destination (google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.To.Destination): + Optional. Describes properties of destination of a request. + Within a destination, the match follows AND semantics across + fields and OR semantics within a field, i.e. a match occurs + when ANY path matches AND ANY header matches and ANY method + matches. At least one of destination or not_destination must + be specified. + not_destination (google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.To.Destination): + Optional. Describes the negated properties of the request + destination. Extension will not be invoked on requests that + match the criteria specified in this field. At least one of + destination or not_destination must be specified. + """ + + class Destination(proto.Message): + r"""Describes properties of a single destination. + + Attributes: + header_set (google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.To.Destination.HeaderSet): + Optional. A set of HTTP headers to match + against. If not specified, requests with any + headers are matched. + resources (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.StringMatch]): + Optional. A list of non-empty strings whose + value is matched against the resource to which a + request is sent (e.g., an Agent in + AiApplication). If not specified, any resource + is allowed. If specified, a match occurs if any + of the resources matches the resource value in + the request. Limited to 5 resources. When + matching against resources in the AgentRegistry, + use the URNs of the registry resources. + hosts (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.StringMatch]): + Optional. A list of HTTP Hosts to match + against. Limited to 10 hosts. If not specified, + any host is allowed. If specified, a match + occurs if any of the hosts matches the host + value in the request. + paths (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.StringMatch]): + Optional. A list of paths to match against. + Limited to 10 paths. If not specified, any path + is allowed. + + Note that this path match includes the query + parameters. For gRPC services, this should be a + fully-qualified name of the form + /package.service/method. + """ + + class HeaderSet(proto.Message): + r"""Describes a set of HTTP headers to match against. + + Attributes: + headers (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionBinding.MatchCondition.HeaderMatch]): + Required. A list of headers to match against + in http header. If multiple header matches are + provided, they will be evaluated as an AND, i.e. + all header matches must match for the request to + match. + """ + + headers: MutableSequence[ + "ExtensionBinding.MatchCondition.HeaderMatch" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ExtensionBinding.MatchCondition.HeaderMatch", + ) + + header_set: "ExtensionBinding.MatchCondition.To.Destination.HeaderSet" = proto.Field( + proto.MESSAGE, + number=1, + message="ExtensionBinding.MatchCondition.To.Destination.HeaderSet", + ) + resources: MutableSequence[ + "ExtensionBinding.MatchCondition.StringMatch" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="ExtensionBinding.MatchCondition.StringMatch", + ) + hosts: MutableSequence[ + "ExtensionBinding.MatchCondition.StringMatch" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="ExtensionBinding.MatchCondition.StringMatch", + ) + paths: MutableSequence[ + "ExtensionBinding.MatchCondition.StringMatch" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="ExtensionBinding.MatchCondition.StringMatch", + ) + + destination: "ExtensionBinding.MatchCondition.To.Destination" = proto.Field( + proto.MESSAGE, + number=1, + message="ExtensionBinding.MatchCondition.To.Destination", + ) + not_destination: "ExtensionBinding.MatchCondition.To.Destination" = ( + proto.Field( + proto.MESSAGE, + number=2, + message="ExtensionBinding.MatchCondition.To.Destination", + ) + ) + + to: "ExtensionBinding.MatchCondition.To" = proto.Field( + proto.MESSAGE, + number=2, + message="ExtensionBinding.MatchCondition.To", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + producer_extension: str = proto.Field( + proto.STRING, + number=7, + ) + target: Target = proto.Field( + proto.MESSAGE, + number=8, + message=Target, + ) + match_conditions: MutableSequence[MatchCondition] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=MatchCondition, + ) + fail_open: bool = proto.Field( + proto.BOOL, + number=10, + ) + producer_metadata: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + priority: int = proto.Field( + proto.INT32, + number=12, + ) + + +class ListExtensionBindingsRequest(proto.Message): + r"""Request used with the ``ListExtensionBindings`` method. + + Attributes: + parent (str): + Required. The project and location from which the + ``ExtensionBinding`` resources should be listed, specified + in the format ``projects/{project}/locations/{location}``. + page_size (int): + Optional. Maximum number of ``ExtensionBinding`` resources + to return per call. + page_token (str): + Optional. The value returned by the last + ``ListExtensionBindingsResponse`` Indicates that this is a + continuation of a prior ``ListExtensionBindings`` call, and + that the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListExtensionBindingsResponse(proto.Message): + r"""Response returned by the ``ListExtensionBindings`` method. + + Attributes: + extension_bindings (MutableSequence[google.cloud.network_services_v1beta1.types.ExtensionBinding]): + List of ``ExtensionBinding`` resources. + next_page_token (str): + If there might be more results than those appearing in this + response, then ``next_page_token`` is included. To get the + next set of results, call this method again using the value + of ``next_page_token`` as ``page_token``. + unreachable (MutableSequence[str]): + Unordered list. Unreachable resources. Populated when the + request attempts to list all resources across all supported + locations, while some locations are temporarily unavailable. + The resource names are in the format + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + """ + + @property + def raw_page(self): + return self + + extension_bindings: MutableSequence["ExtensionBinding"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ExtensionBinding", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetExtensionBindingRequest(proto.Message): + r"""Request used by the ``GetExtensionBinding`` method. + + Attributes: + name (str): + Required. A name of the ``ExtensionBinding`` resource to + get. Must be in the format + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateExtensionBindingRequest(proto.Message): + r"""Request used by the ``CreateExtensionBinding`` method. + + Attributes: + parent (str): + Required. The parent resource of the ``ExtensionBinding`` + resource. Must be in the format + ``projects/{project}/locations/{location}``. + extension_binding_id (str): + Required. Short name of the ``ExtensionBinding`` resource to + be created. + extension_binding (google.cloud.network_services_v1beta1.types.ExtensionBinding): + Required. ``ExtensionBinding`` resource to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + extension_binding_id: str = proto.Field( + proto.STRING, + number=2, + ) + extension_binding: "ExtensionBinding" = proto.Field( + proto.MESSAGE, + number=3, + message="ExtensionBinding", + ) + + +class UpdateExtensionBindingRequest(proto.Message): + r"""Request used by the ``UpdateExtensionBinding`` method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ``ExtensionBinding`` resource by the + update. The fields specified in the update_mask are relative + to the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + extension_binding (google.cloud.network_services_v1beta1.types.ExtensionBinding): + Required. Updated ``ExtensionBinding`` resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + extension_binding: "ExtensionBinding" = proto.Field( + proto.MESSAGE, + number=2, + message="ExtensionBinding", + ) + + +class DeleteExtensionBindingRequest(proto.Message): + r"""Request used by the ``DeleteExtensionBinding`` method. + + Attributes: + name (str): + Required. A name of the ``ExtensionBinding`` resource to + delete. Must be in the format + ``projects/{project}/locations/{location}/extensionBindings/{extension_binding}``. + etag (str): + Optional. The etag of the ExtensionBinding to + delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/endpoint_policy.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/endpoint_policy.py new file mode 100644 index 000000000000..2034b73094dd --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/endpoint_policy.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.network_services_v1beta1.types import common + +__protobuf__ = proto.module( + package="google.cloud.networkservices.v1beta1", + manifest={ + "EndpointPolicy", + "ListEndpointPoliciesRequest", + "ListEndpointPoliciesResponse", + "GetEndpointPolicyRequest", + "CreateEndpointPolicyRequest", + "UpdateEndpointPolicyRequest", + "DeleteEndpointPolicyRequest", + }, +) + + +class EndpointPolicy(proto.Message): + r"""EndpointPolicy is a resource that helps apply desired + configuration on the endpoints that match specific criteria. For + example, this resource can be used to apply "authentication + config" an all endpoints that serve on port 8080. + + Attributes: + name (str): + Required. Name of the EndpointPolicy resource. It matches + pattern + ``projects/{project}/locations/global/endpointPolicies/{endpoint_policy}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the EndpointPolicy resource. + type_ (google.cloud.network_services_v1beta1.types.EndpointPolicy.EndpointPolicyType): + Required. The type of endpoint policy. This + is primarily used to validate the configuration. + authorization_policy (str): + Optional. This field specifies the URL of + AuthorizationPolicy resource that applies + authorization policies to the inbound traffic at + the matched endpoints. Refer to Authorization. + If this field is not specified, authorization is + disabled(no authz checks) for this endpoint. + endpoint_matcher (google.cloud.network_services_v1beta1.types.EndpointMatcher): + Required. A matcher that selects endpoints to + which the policies should be applied. + traffic_port_selector (google.cloud.network_services_v1beta1.types.TrafficPortSelector): + Optional. Port selector for the (matched) + endpoints. If no port selector is provided, the + matched config is applied to all ports. + description (str): + Optional. A free-text description of the + resource. Max length 1024 characters. + server_tls_policy (str): + Optional. A URL referring to ServerTlsPolicy + resource. ServerTlsPolicy is used to determine + the authentication policy to be applied to + terminate the inbound traffic at the identified + backends. If this field is not set, + authentication is disabled(open) for this + endpoint. + client_tls_policy (str): + Optional. Deprecated: This field is not used and is a no-op. + A URL referring to a ClientTlsPolicy resource. + ClientTlsPolicy can be set to specify the authentication for + traffic from the proxy to the actual endpoints. More + specifically, it is applied to the outgoing traffic from the + proxy to the endpoint. This is typically used for sidecar + model where the proxy identifies itself as endpoint to the + control plane, with the connection between sidecar and + endpoint requiring authentication. If this field is not set, + authentication is disabled(open). Applicable only when + EndpointPolicyType is SIDECAR_PROXY. + """ + + class EndpointPolicyType(proto.Enum): + r"""The type of endpoint policy. + + Values: + ENDPOINT_POLICY_TYPE_UNSPECIFIED (0): + Default value. Must not be used. + SIDECAR_PROXY (1): + Represents a proxy deployed as a sidecar. + GRPC_SERVER (2): + Represents a proxyless gRPC backend. + """ + + ENDPOINT_POLICY_TYPE_UNSPECIFIED = 0 + SIDECAR_PROXY = 1 + GRPC_SERVER = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + type_: EndpointPolicyType = proto.Field( + proto.ENUM, + number=5, + enum=EndpointPolicyType, + ) + authorization_policy: str = proto.Field( + proto.STRING, + number=7, + ) + endpoint_matcher: common.EndpointMatcher = proto.Field( + proto.MESSAGE, + number=9, + message=common.EndpointMatcher, + ) + traffic_port_selector: common.TrafficPortSelector = proto.Field( + proto.MESSAGE, + number=10, + message=common.TrafficPortSelector, + ) + description: str = proto.Field( + proto.STRING, + number=11, + ) + server_tls_policy: str = proto.Field( + proto.STRING, + number=12, + ) + client_tls_policy: str = proto.Field( + proto.STRING, + number=13, + ) + + +class ListEndpointPoliciesRequest(proto.Message): + r"""Request used with the ListEndpointPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + EndpointPolicies should be listed, specified in the format + ``projects/*/locations/global``. + page_size (int): + Maximum number of EndpointPolicies to return + per call. + page_token (str): + The value returned by the last + ``ListEndpointPoliciesResponse`` Indicates that this is a + continuation of a prior ``ListEndpointPolicies`` call, and + that the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEndpointPoliciesResponse(proto.Message): + r"""Response returned by the ListEndpointPolicies method. + + Attributes: + endpoint_policies (MutableSequence[google.cloud.network_services_v1beta1.types.EndpointPolicy]): + List of EndpointPolicy resources. + next_page_token (str): + If there might be more results than those appearing in this + response, then ``next_page_token`` is included. To get the + next set of results, call this method again using the value + of ``next_page_token`` as ``page_token``. + """ + + @property + def raw_page(self): + return self + + endpoint_policies: MutableSequence["EndpointPolicy"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="EndpointPolicy", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEndpointPolicyRequest(proto.Message): + r"""Request used with the GetEndpointPolicy method. + + Attributes: + name (str): + Required. A name of the EndpointPolicy to get. Must be in + the format + ``projects/*/locations/global/endpointPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEndpointPolicyRequest(proto.Message): + r"""Request used with the CreateEndpointPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the EndpointPolicy. Must be + in the format ``projects/*/locations/global``. + endpoint_policy_id (str): + Required. Short name of the EndpointPolicy + resource to be created. E.g. "CustomECS". + endpoint_policy (google.cloud.network_services_v1beta1.types.EndpointPolicy): + Required. EndpointPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + endpoint_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + endpoint_policy: "EndpointPolicy" = proto.Field( + proto.MESSAGE, + number=3, + message="EndpointPolicy", + ) + + +class UpdateEndpointPolicyRequest(proto.Message): + r"""Request used with the UpdateEndpointPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the EndpointPolicy resource by the update. + The fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + endpoint_policy (google.cloud.network_services_v1beta1.types.EndpointPolicy): + Required. Updated EndpointPolicy resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + endpoint_policy: "EndpointPolicy" = proto.Field( + proto.MESSAGE, + number=2, + message="EndpointPolicy", + ) + + +class DeleteEndpointPolicyRequest(proto.Message): + r"""Request used with the DeleteEndpointPolicy method. + + Attributes: + name (str): + Required. A name of the EndpointPolicy to delete. Must be in + the format + ``projects/*/locations/global/endpointPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/network_services.py b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/network_services.py new file mode 100644 index 000000000000..c852b3b1bc85 --- /dev/null +++ b/packages/google-cloud-network-services/google/cloud/network_services_v1beta1/types/network_services.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.networkservices.v1beta1", + manifest={}, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_extension_binding_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_extension_binding_async.py new file mode 100644 index 000000000000..52c9d417d009 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_extension_binding_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_CreateExtensionBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_create_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.CreateExtensionBindingRequest( + parent="parent_value", + extension_binding_id="extension_binding_id_value", + extension_binding=extension_binding, + ) + + # Make the request + operation = await client.create_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_CreateExtensionBinding_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_extension_binding_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_extension_binding_sync.py new file mode 100644 index 000000000000..ead7852173c1 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_extension_binding_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_CreateExtensionBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_create_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.CreateExtensionBindingRequest( + parent="parent_value", + extension_binding_id="extension_binding_id_value", + extension_binding=extension_binding, + ) + + # Make the request + operation = client.create_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_CreateExtensionBinding_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_route_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_route_extension_async.py new file mode 100644 index 000000000000..418d7a39e61e --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_route_extension_async.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_CreateLbRouteExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = await client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_CreateLbRouteExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_route_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_route_extension_sync.py new file mode 100644 index 000000000000..b5214e804fdd --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_route_extension_sync.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_CreateLbRouteExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_create_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.create_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_CreateLbRouteExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_async.py new file mode 100644 index 000000000000..293326c4ec68 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_async.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_CreateLbTrafficExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = await client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_CreateLbTrafficExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..d0057a674c90 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_sync.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_CreateLbTrafficExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_create_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.create_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_CreateLbTrafficExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_extension_binding_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_extension_binding_async.py new file mode 100644 index 000000000000..4a2a9f78586b --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_extension_binding_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_DeleteExtensionBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_delete_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteExtensionBindingRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_DeleteExtensionBinding_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_extension_binding_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_extension_binding_sync.py new file mode 100644 index 000000000000..2ed06bf79ace --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_extension_binding_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_DeleteExtensionBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_delete_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteExtensionBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_DeleteExtensionBinding_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_async.py new file mode 100644 index 000000000000..6d459589a658 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_DeleteLbRouteExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_DeleteLbRouteExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_sync.py new file mode 100644 index 000000000000..450c04d77c99 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_DeleteLbRouteExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_delete_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_DeleteLbRouteExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_async.py new file mode 100644 index 000000000000..076739f98574 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_DeleteLbTrafficExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_DeleteLbTrafficExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..f662913cc42e --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_DeleteLbTrafficExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_delete_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_DeleteLbTrafficExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_extension_binding_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_extension_binding_async.py new file mode 100644 index 000000000000..91723265d35c --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_extension_binding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_GetExtensionBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_get_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetExtensionBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_extension_binding(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_GetExtensionBinding_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_extension_binding_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_extension_binding_sync.py new file mode 100644 index 000000000000..e94433913260 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_extension_binding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_GetExtensionBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_get_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetExtensionBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_extension_binding(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_GetExtensionBinding_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_route_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_route_extension_async.py new file mode 100644 index 000000000000..01d8b077dbc0 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_route_extension_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_GetLbRouteExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_GetLbRouteExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_route_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_route_extension_sync.py new file mode 100644 index 000000000000..431cbdf2ccb0 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_route_extension_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_GetLbRouteExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_get_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_route_extension(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_GetLbRouteExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_async.py new file mode 100644 index 000000000000..f5c2e665a536 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_GetLbTrafficExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_GetLbTrafficExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..60f4d3d462d4 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_GetLbTrafficExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_get_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_lb_traffic_extension(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_GetLbTrafficExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_extension_bindings_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_extension_bindings_async.py new file mode 100644 index 000000000000..635e6692491b --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_extension_bindings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListExtensionBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_ListExtensionBindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_list_extension_bindings(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListExtensionBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_extension_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_DepService_ListExtensionBindings_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_extension_bindings_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_extension_bindings_sync.py new file mode 100644 index 000000000000..e3708fe7cd8b --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_extension_bindings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListExtensionBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_ListExtensionBindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_list_extension_bindings(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListExtensionBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_extension_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_DepService_ListExtensionBindings_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_async.py new file mode 100644 index 000000000000..233df0c8cb66 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbRouteExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_ListLbRouteExtensions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_DepService_ListLbRouteExtensions_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_sync.py new file mode 100644 index 000000000000..8f4289562620 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbRouteExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_ListLbRouteExtensions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_list_lb_route_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbRouteExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_route_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_DepService_ListLbRouteExtensions_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_async.py new file mode 100644 index 000000000000..5bc659569e69 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbTrafficExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_ListLbTrafficExtensions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_DepService_ListLbTrafficExtensions_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_sync.py new file mode 100644 index 000000000000..8e1ec5839a82 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListLbTrafficExtensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_ListLbTrafficExtensions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_list_lb_traffic_extensions(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListLbTrafficExtensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_lb_traffic_extensions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_DepService_ListLbTrafficExtensions_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_extension_binding_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_extension_binding_async.py new file mode 100644 index 000000000000..68368ab054c4 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_extension_binding_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_UpdateExtensionBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_update_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.UpdateExtensionBindingRequest( + extension_binding=extension_binding, + ) + + # Make the request + operation = await client.update_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_UpdateExtensionBinding_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_extension_binding_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_extension_binding_sync.py new file mode 100644 index 000000000000..0ec5576186c1 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_extension_binding_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateExtensionBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_UpdateExtensionBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_update_extension_binding(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + extension_binding = network_services_v1beta1.ExtensionBinding() + extension_binding.producer_extension = "producer_extension_value" + + request = network_services_v1beta1.UpdateExtensionBindingRequest( + extension_binding=extension_binding, + ) + + # Make the request + operation = client.update_extension_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_UpdateExtensionBinding_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_route_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_route_extension_async.py new file mode 100644 index 000000000000..b17f2a267313 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_route_extension_async.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_UpdateLbRouteExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = await client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_UpdateLbRouteExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_route_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_route_extension_sync.py new file mode 100644 index 000000000000..d42d02d1f109 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_route_extension_sync.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbRouteExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_UpdateLbRouteExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_update_lb_route_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_route_extension = network_services_v1beta1.LbRouteExtension() + lb_route_extension.name = "name_value" + lb_route_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_route_extension.extension_chains.name = "name_value" + lb_route_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_route_extension.extension_chains.extensions.name = "name_value" + lb_route_extension.extension_chains.extensions.service = "service_value" + lb_route_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbRouteExtensionRequest( + lb_route_extension=lb_route_extension, + ) + + # Make the request + operation = client.update_lb_route_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_UpdateLbRouteExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_async.py new file mode 100644 index 000000000000..165ab9d43991 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_async.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_UpdateLbTrafficExtension_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceAsyncClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = await client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_UpdateLbTrafficExtension_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_sync.py new file mode 100644 index 000000000000..2770554e7341 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_sync.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateLbTrafficExtension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_DepService_UpdateLbTrafficExtension_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_update_lb_traffic_extension(): + # Create a client + client = network_services_v1beta1.DepServiceClient() + + # Initialize request argument(s) + lb_traffic_extension = network_services_v1beta1.LbTrafficExtension() + lb_traffic_extension.name = "name_value" + lb_traffic_extension.forwarding_rules = [ + "forwarding_rules_value1", + "forwarding_rules_value2", + ] + lb_traffic_extension.extension_chains.name = "name_value" + lb_traffic_extension.extension_chains.match_condition.cel_expression = ( + "cel_expression_value" + ) + lb_traffic_extension.extension_chains.extensions.name = "name_value" + lb_traffic_extension.extension_chains.extensions.service = "service_value" + lb_traffic_extension.load_balancing_scheme = "EXTERNAL_MANAGED" + + request = network_services_v1beta1.UpdateLbTrafficExtensionRequest( + lb_traffic_extension=lb_traffic_extension, + ) + + # Make the request + operation = client.update_lb_traffic_extension(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_DepService_UpdateLbTrafficExtension_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_create_endpoint_policy_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_create_endpoint_policy_async.py new file mode 100644 index 000000000000..f032f3c169a0 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_create_endpoint_policy_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_CreateEndpointPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = await client.create_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_CreateEndpointPolicy_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_create_endpoint_policy_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_create_endpoint_policy_sync.py new file mode 100644 index 000000000000..0ff044e2fa05 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_create_endpoint_policy_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_CreateEndpointPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_create_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.create_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_CreateEndpointPolicy_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_delete_endpoint_policy_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_delete_endpoint_policy_async.py new file mode 100644 index 000000000000..8b585711cd1d --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_delete_endpoint_policy_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_DeleteEndpointPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_DeleteEndpointPolicy_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_delete_endpoint_policy_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_delete_endpoint_policy_sync.py new file mode 100644 index 000000000000..883064591818 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_delete_endpoint_policy_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_DeleteEndpointPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_delete_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1beta1.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_DeleteEndpointPolicy_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_get_endpoint_policy_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_get_endpoint_policy_async.py new file mode 100644 index 000000000000..e09ae024c1e8 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_get_endpoint_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_GetEndpointPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_GetEndpointPolicy_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_get_endpoint_policy_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_get_endpoint_policy_sync.py new file mode 100644 index 000000000000..e454ccc8d0c3 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_get_endpoint_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_GetEndpointPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_get_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1beta1.GetEndpointPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_endpoint_policy(request=request) + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_GetEndpointPolicy_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_list_endpoint_policies_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_list_endpoint_policies_async.py new file mode 100644 index 000000000000..caa1c72886d9 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_list_endpoint_policies_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEndpointPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_ListEndpointPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_ListEndpointPolicies_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_list_endpoint_policies_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_list_endpoint_policies_sync.py new file mode 100644 index 000000000000..8cd48e63c734 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_list_endpoint_policies_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEndpointPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_ListEndpointPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_list_endpoint_policies(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + request = network_services_v1beta1.ListEndpointPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_endpoint_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_ListEndpointPolicies_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_update_endpoint_policy_async.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_update_endpoint_policy_async.py new file mode 100644 index 000000000000..d130efc9987c --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_update_endpoint_policy_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_UpdateEndpointPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +async def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesAsyncClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = await client.update_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_UpdateEndpointPolicy_async] diff --git a/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_update_endpoint_policy_sync.py b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_update_endpoint_policy_sync.py new file mode 100644 index 000000000000..3d0a6b2aa48b --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/networkservices_v1beta1_generated_network_services_update_endpoint_policy_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEndpointPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-services + + +# [START networkservices_v1beta1_generated_NetworkServices_UpdateEndpointPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_services_v1beta1 + + +def sample_update_endpoint_policy(): + # Create a client + client = network_services_v1beta1.NetworkServicesClient() + + # Initialize request argument(s) + endpoint_policy = network_services_v1beta1.EndpointPolicy() + endpoint_policy.name = "name_value" + endpoint_policy.type_ = "GRPC_SERVER" + + request = network_services_v1beta1.UpdateEndpointPolicyRequest( + endpoint_policy=endpoint_policy, + ) + + # Make the request + operation = client.update_endpoint_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networkservices_v1beta1_generated_NetworkServices_UpdateEndpointPolicy_sync] diff --git a/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json b/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json index b96313b1421a..082dcd2de984 100644 --- a/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json +++ b/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-services", - "version": "0.10.2" + "version": "0.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1beta1.json b/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1beta1.json new file mode 100644 index 000000000000..f1c174989bc1 --- /dev/null +++ b/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1beta1.json @@ -0,0 +1,3331 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.networkservices.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-network-services", + "version": "0.10.3" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.create_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.CreateExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateExtensionBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "extension_binding", + "type": "google.cloud.network_services_v1beta1.types.ExtensionBinding" + }, + { + "name": "extension_binding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_extension_binding" + }, + "description": "Sample for CreateExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_create_extension_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_CreateExtensionBinding_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_create_extension_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.create_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.CreateExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateExtensionBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "extension_binding", + "type": "google.cloud.network_services_v1beta1.types.ExtensionBinding" + }, + { + "name": "extension_binding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_extension_binding" + }, + "description": "Sample for CreateExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_create_extension_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_CreateExtensionBinding_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_create_extension_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.create_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.CreateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateLbRouteExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1beta1.types.LbRouteExtension" + }, + { + "name": "lb_route_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_lb_route_extension" + }, + "description": "Sample for CreateLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_create_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_CreateLbRouteExtension_async", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_create_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.create_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.CreateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateLbRouteExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1beta1.types.LbRouteExtension" + }, + { + "name": "lb_route_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_lb_route_extension" + }, + "description": "Sample for CreateLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_create_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_CreateLbRouteExtension_sync", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_create_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.create_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.CreateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateLbTrafficExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1beta1.types.LbTrafficExtension" + }, + { + "name": "lb_traffic_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_lb_traffic_extension" + }, + "description": "Sample for CreateLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_CreateLbTrafficExtension_async", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.create_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.CreateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "CreateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateLbTrafficExtensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1beta1.types.LbTrafficExtension" + }, + { + "name": "lb_traffic_extension_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_lb_traffic_extension" + }, + "description": "Sample for CreateLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_CreateLbTrafficExtension_sync", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 56, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 63, + "start": 57, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 64, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_create_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.delete_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.DeleteExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteExtensionBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_extension_binding" + }, + "description": "Sample for DeleteExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_delete_extension_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_DeleteExtensionBinding_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_delete_extension_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.delete_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.DeleteExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteExtensionBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_extension_binding" + }, + "description": "Sample for DeleteExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_delete_extension_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_DeleteExtensionBinding_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_delete_extension_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.delete_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.DeleteLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_lb_route_extension" + }, + "description": "Sample for DeleteLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_DeleteLbRouteExtension_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.delete_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.DeleteLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_lb_route_extension" + }, + "description": "Sample for DeleteLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_DeleteLbRouteExtension_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_delete_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.delete_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.DeleteLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_lb_traffic_extension" + }, + "description": "Sample for DeleteLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_DeleteLbTrafficExtension_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.delete_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.DeleteLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "DeleteLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_lb_traffic_extension" + }, + "description": "Sample for DeleteLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_DeleteLbTrafficExtension_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_delete_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.get_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.GetExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "GetExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetExtensionBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.ExtensionBinding", + "shortName": "get_extension_binding" + }, + "description": "Sample for GetExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_get_extension_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_GetExtensionBinding_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_get_extension_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.get_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.GetExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "GetExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetExtensionBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.ExtensionBinding", + "shortName": "get_extension_binding" + }, + "description": "Sample for GetExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_get_extension_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_GetExtensionBinding_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_get_extension_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.get_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.GetLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.LbRouteExtension", + "shortName": "get_lb_route_extension" + }, + "description": "Sample for GetLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_get_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_GetLbRouteExtension_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_get_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.get_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.GetLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetLbRouteExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.LbRouteExtension", + "shortName": "get_lb_route_extension" + }, + "description": "Sample for GetLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_get_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_GetLbRouteExtension_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_get_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.get_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.GetLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.LbTrafficExtension", + "shortName": "get_lb_traffic_extension" + }, + "description": "Sample for GetLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_GetLbTrafficExtension_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.get_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.GetLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "GetLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetLbTrafficExtensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.LbTrafficExtension", + "shortName": "get_lb_traffic_extension" + }, + "description": "Sample for GetLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_GetLbTrafficExtension_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_get_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.list_extension_bindings", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.ListExtensionBindings", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "ListExtensionBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListExtensionBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.dep_service.pagers.ListExtensionBindingsAsyncPager", + "shortName": "list_extension_bindings" + }, + "description": "Sample for ListExtensionBindings", + "file": "networkservices_v1beta1_generated_dep_service_list_extension_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_ListExtensionBindings_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_list_extension_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.list_extension_bindings", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.ListExtensionBindings", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "ListExtensionBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListExtensionBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.dep_service.pagers.ListExtensionBindingsPager", + "shortName": "list_extension_bindings" + }, + "description": "Sample for ListExtensionBindings", + "file": "networkservices_v1beta1_generated_dep_service_list_extension_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_ListExtensionBindings_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_list_extension_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.list_lb_route_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.ListLbRouteExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbRouteExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbRouteExtensionsAsyncPager", + "shortName": "list_lb_route_extensions" + }, + "description": "Sample for ListLbRouteExtensions", + "file": "networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_ListLbRouteExtensions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.list_lb_route_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.ListLbRouteExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbRouteExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListLbRouteExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbRouteExtensionsPager", + "shortName": "list_lb_route_extensions" + }, + "description": "Sample for ListLbRouteExtensions", + "file": "networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_ListLbRouteExtensions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_list_lb_route_extensions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.list_lb_traffic_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.ListLbTrafficExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbTrafficExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbTrafficExtensionsAsyncPager", + "shortName": "list_lb_traffic_extensions" + }, + "description": "Sample for ListLbTrafficExtensions", + "file": "networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_ListLbTrafficExtensions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.list_lb_traffic_extensions", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.ListLbTrafficExtensions", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "ListLbTrafficExtensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListLbTrafficExtensionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.dep_service.pagers.ListLbTrafficExtensionsPager", + "shortName": "list_lb_traffic_extensions" + }, + "description": "Sample for ListLbTrafficExtensions", + "file": "networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_ListLbTrafficExtensions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_list_lb_traffic_extensions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.update_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.UpdateExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateExtensionBindingRequest" + }, + { + "name": "extension_binding", + "type": "google.cloud.network_services_v1beta1.types.ExtensionBinding" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_extension_binding" + }, + "description": "Sample for UpdateExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_update_extension_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_UpdateExtensionBinding_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_update_extension_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.update_extension_binding", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.UpdateExtensionBinding", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateExtensionBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateExtensionBindingRequest" + }, + { + "name": "extension_binding", + "type": "google.cloud.network_services_v1beta1.types.ExtensionBinding" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_extension_binding" + }, + "description": "Sample for UpdateExtensionBinding", + "file": "networkservices_v1beta1_generated_dep_service_update_extension_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_UpdateExtensionBinding_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_update_extension_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.update_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.UpdateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateLbRouteExtensionRequest" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1beta1.types.LbRouteExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_lb_route_extension" + }, + "description": "Sample for UpdateLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_update_lb_route_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_UpdateLbRouteExtension_async", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_update_lb_route_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.update_lb_route_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.UpdateLbRouteExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbRouteExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateLbRouteExtensionRequest" + }, + { + "name": "lb_route_extension", + "type": "google.cloud.network_services_v1beta1.types.LbRouteExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_lb_route_extension" + }, + "description": "Sample for UpdateLbRouteExtension", + "file": "networkservices_v1beta1_generated_dep_service_update_lb_route_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_UpdateLbRouteExtension_sync", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_update_lb_route_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient", + "shortName": "DepServiceAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceAsyncClient.update_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.UpdateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateLbTrafficExtensionRequest" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1beta1.types.LbTrafficExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_lb_traffic_extension" + }, + "description": "Sample for UpdateLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_UpdateLbTrafficExtension_async", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient", + "shortName": "DepServiceClient" + }, + "fullName": "google.cloud.network_services_v1beta1.DepServiceClient.update_lb_traffic_extension", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.DepService.UpdateLbTrafficExtension", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.DepService", + "shortName": "DepService" + }, + "shortName": "UpdateLbTrafficExtension" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateLbTrafficExtensionRequest" + }, + { + "name": "lb_traffic_extension", + "type": "google.cloud.network_services_v1beta1.types.LbTrafficExtension" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_lb_traffic_extension" + }, + "description": "Sample for UpdateLbTrafficExtension", + "file": "networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_DepService_UpdateLbTrafficExtension_sync", + "segments": [ + { + "end": 64, + "start": 27, + "type": "FULL" + }, + { + "end": 64, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 54, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 55, + "type": "REQUEST_EXECUTION" + }, + { + "end": 65, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_dep_service_update_lb_traffic_extension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient.create_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.CreateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateEndpointPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1beta1.types.EndpointPolicy" + }, + { + "name": "endpoint_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_endpoint_policy" + }, + "description": "Sample for CreateEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_create_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_CreateEndpointPolicy_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_create_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient.create_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.CreateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "CreateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.CreateEndpointPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1beta1.types.EndpointPolicy" + }, + { + "name": "endpoint_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_endpoint_policy" + }, + "description": "Sample for CreateEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_create_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_CreateEndpointPolicy_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_create_endpoint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient.delete_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.DeleteEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_endpoint_policy" + }, + "description": "Sample for DeleteEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_delete_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_DeleteEndpointPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_delete_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient.delete_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.DeleteEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "DeleteEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.DeleteEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_endpoint_policy" + }, + "description": "Sample for DeleteEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_delete_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_DeleteEndpointPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_delete_endpoint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient.get_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.GetEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.EndpointPolicy", + "shortName": "get_endpoint_policy" + }, + "description": "Sample for GetEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_get_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_GetEndpointPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_get_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient.get_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.GetEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "GetEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.GetEndpointPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.types.EndpointPolicy", + "shortName": "get_endpoint_policy" + }, + "description": "Sample for GetEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_get_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_GetEndpointPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_get_endpoint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient.list_endpoint_policies", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.ListEndpointPolicies", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListEndpointPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListEndpointPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.network_services.pagers.ListEndpointPoliciesAsyncPager", + "shortName": "list_endpoint_policies" + }, + "description": "Sample for ListEndpointPolicies", + "file": "networkservices_v1beta1_generated_network_services_list_endpoint_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_ListEndpointPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_list_endpoint_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient.list_endpoint_policies", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.ListEndpointPolicies", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "ListEndpointPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.ListEndpointPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_services_v1beta1.services.network_services.pagers.ListEndpointPoliciesPager", + "shortName": "list_endpoint_policies" + }, + "description": "Sample for ListEndpointPolicies", + "file": "networkservices_v1beta1_generated_network_services_list_endpoint_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_ListEndpointPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_list_endpoint_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient", + "shortName": "NetworkServicesAsyncClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesAsyncClient.update_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.UpdateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateEndpointPolicyRequest" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1beta1.types.EndpointPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_endpoint_policy" + }, + "description": "Sample for UpdateEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_update_endpoint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_UpdateEndpointPolicy_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_update_endpoint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient", + "shortName": "NetworkServicesClient" + }, + "fullName": "google.cloud.network_services_v1beta1.NetworkServicesClient.update_endpoint_policy", + "method": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices.UpdateEndpointPolicy", + "service": { + "fullName": "google.cloud.networkservices.v1beta1.NetworkServices", + "shortName": "NetworkServices" + }, + "shortName": "UpdateEndpointPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_services_v1beta1.types.UpdateEndpointPolicyRequest" + }, + { + "name": "endpoint_policy", + "type": "google.cloud.network_services_v1beta1.types.EndpointPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_endpoint_policy" + }, + "description": "Sample for UpdateEndpointPolicy", + "file": "networkservices_v1beta1_generated_network_services_update_endpoint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkservices_v1beta1_generated_NetworkServices_UpdateEndpointPolicy_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkservices_v1beta1_generated_network_services_update_endpoint_policy_sync.py" + } + ] +} diff --git a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/__init__.py b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_compat.py b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_compat.py new file mode 100644 index 000000000000..4ab3a0b02fea --- /dev/null +++ b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_compat.py @@ -0,0 +1,429 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Tests for the compatibility module for older versions of google-api-core.""" + +import json +import os +from unittest import mock + +import google.auth.transport.mtls +import pytest +from google.api_core.universe import EmptyUniverseError +from google.auth.exceptions import MutualTLSChannelError +from google.protobuf import descriptor_pb2 + +from google.cloud.network_services_v1beta1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, + transcode_request, +) + + +def test_get_universe_domain(): + # When universe_domain is provided + assert get_universe_domain("foo.com", default_universe="default.com") == "foo.com" + assert ( + get_universe_domain(" foo.com ", default_universe="default.com") == "foo.com" + ) + + # When universe_domain is None, falls back to default_universe + assert get_universe_domain(None, default_universe="default.com") == "default.com" + + # When multiple potential universes are provided, resolves in order of preference + assert ( + get_universe_domain("foo.com", "bar.com", default_universe="default.com") + == "foo.com" + ) + assert ( + get_universe_domain(None, "bar.com", default_universe="default.com") + == "bar.com" + ) + assert ( + get_universe_domain(None, None, default_universe="default.com") == "default.com" + ) + + # EmptyUniverseError raised when resolved value is empty string + with pytest.raises(EmptyUniverseError) as excinfo: + get_universe_domain("", default_universe="default.com") + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + with pytest.raises(EmptyUniverseError) as excinfo: + get_universe_domain(" ", default_universe="default.com") + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + with pytest.raises(EmptyUniverseError) as excinfo: + get_universe_domain(None, "", default_universe="default.com") + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +def test_get_default_mtls_endpoint(): + # Test valid API endpoints + assert get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" + assert ( + get_default_mtls_endpoint("foo.sandbox.googleapis.com") + == "foo.mtls.sandbox.googleapis.com" + ) + # Test case-insensitivity + assert get_default_mtls_endpoint("foo.GoogleAPIs.com") == "foo.mtls.googleapis.com" + assert ( + get_default_mtls_endpoint("foo.Sandbox.GoogleAPIs.com") + == "foo.mtls.sandbox.googleapis.com" + ) + + # Test valid API endpoints with schemes + assert ( + get_default_mtls_endpoint("https://foo.googleapis.com") + == "https://foo.mtls.googleapis.com" + ) + assert ( + get_default_mtls_endpoint("http://foo.googleapis.com:8080/v1") + == "http://foo.mtls.googleapis.com:8080/v1" + ) + + # Test valid API endpoints with ports + assert ( + get_default_mtls_endpoint("foo.googleapis.com:443") + == "foo.mtls.googleapis.com:443" + ) + assert ( + get_default_mtls_endpoint("foo.sandbox.googleapis.com:443") + == "foo.mtls.sandbox.googleapis.com:443" + ) + # Test case-insensitivity with ports + assert ( + get_default_mtls_endpoint("foo.GoogleAPIs.com:443") + == "foo.mtls.googleapis.com:443" + ) + assert ( + get_default_mtls_endpoint("foo.Sandbox.GoogleAPIs.com:443") + == "foo.mtls.sandbox.googleapis.com:443" + ) + + # Test endpoints that shouldn't be converted + assert ( + get_default_mtls_endpoint("foo.mtls.googleapis.com") + == "foo.mtls.googleapis.com" + ) + assert get_default_mtls_endpoint("foo.com") == "foo.com" + assert get_default_mtls_endpoint("foo.com:8080") == "foo.com:8080" + + # Test empty/None endpoints + assert get_default_mtls_endpoint("") == "" + assert get_default_mtls_endpoint(None) is None + + # Test endpoints without host + assert get_default_mtls_endpoint("http://") == "http://" + assert get_default_mtls_endpoint("https://") == "https://" + + +@pytest.mark.parametrize( + "api_override,universe_domain,default_universe,default_mtls_endpoint,default_endpoint_template,use_mtls,expected", + [ + ( + "foo.com", + "googleapis.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + True, + "foo.com", + ), + ( + None, + "googleapis.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + True, + "foo.mtls.googleapis.com", + ), + ( + None, + "googleapis.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + False, + "foo.googleapis.com", + ), + ( + None, + "bar.com", + "googleapis.com", + "foo.mtls.googleapis.com", + "foo.{UNIVERSE_DOMAIN}", + True, + MutualTLSChannelError, + ), + ( + None, + "googleapis.com", + "googleapis.com", + None, + "foo.{UNIVERSE_DOMAIN}", + True, + ValueError, + ), + ], +) +def test_get_api_endpoint( + api_override, + universe_domain, + default_universe, + default_mtls_endpoint, + default_endpoint_template, + use_mtls, + expected, +): + if isinstance(expected, type) and issubclass(expected, Exception): + with pytest.raises(expected): + get_api_endpoint( + api_override, + universe_domain, + default_universe, + default_mtls_endpoint, + default_endpoint_template, + use_mtls, + ) + else: + assert ( + get_api_endpoint( + api_override, + universe_domain, + default_universe, + default_mtls_endpoint, + default_endpoint_template, + use_mtls, + ) + == expected + ) + + +def test_should_use_client_cert_fallback_env(): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}, clear=True + ): + assert should_use_client_cert() is True + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}, clear=True + ): + assert should_use_client_cert() is False + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"}, clear=True + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises( + ValueError, + match="Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`", + ): + should_use_client_cert() + + +def test_transcode_basic(): + # We use FieldDescriptorProto as it has standard primitive fields and nested messages. + http_options = [ + { + "method": "get", + "uri": "/v1/test/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.number = 123 + + transcoded, body, query_params = transcode_request(http_options, request) + + assert transcoded["method"] == "get" + assert transcoded["uri"] == "/v1/test/my-field" + assert body is None + # 'number' should be in query parameters + assert "number" in query_params + assert query_params["number"] == 123 + + +def test_transcode_with_nested_field(): + http_options = [ + { + "method": "get", + "uri": "/v1/test/{options.deprecated}/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.options.deprecated = True + request.number = 123 + + transcoded, body, query_params = transcode_request(http_options, request) + + assert transcoded["method"] == "get" + assert transcoded["uri"] == "/v1/test/True/my-field" + assert body is None + assert "number" in query_params + assert query_params["number"] == 123 + + +def test_transcode_with_body(): + http_options = [ + { + "method": "post", + "uri": "/v1/test/{name}", + "body": "options", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.options.deprecated = True + request.number = 123 + + transcoded, body, query_params = transcode_request(http_options, request) + + assert transcoded["method"] == "post" + assert transcoded["uri"] == "/v1/test/my-field" + assert body is not None + body_data = json.loads(body) + assert body_data["deprecated"] is True + # Query parameters should not contain 'options' (the body) + assert "number" in query_params + assert query_params["number"] == 123 + assert "options" not in query_params + + +def test_transcode_with_required_fields_default_values(): + http_options = [ + { + "method": "get", + "uri": "/v1/test/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + + required_defaults = {"requiredQueryParam": "default-val"} + + transcoded, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=required_defaults, + ) + + assert query_params["requiredQueryParam"] == "default-val" + + +def test_transcode_with_numeric_enums(): + http_options = [ + { + "method": "get", + "uri": "/v1/test/{name}", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "my-field" + request.type = descriptor_pb2.FieldDescriptorProto.TYPE_STRING + + # Without numeric enums + _, _, query_params = transcode_request( + http_options, request, rest_numeric_enums=False + ) + assert query_params["type"] == "TYPE_STRING" + + # With numeric enums + _, _, query_params = transcode_request( + http_options, request, rest_numeric_enums=True + ) + # Type number for TYPE_STRING is 9 + assert query_params["type"] == 9 + assert query_params["$alt"] == "json;enum-encoding=int" + + +def test_transcode_no_query_params(): + http_options = [{"method": "get", "uri": "/v1/test"}] + request = descriptor_pb2.FieldDescriptorProto() + + with mock.patch( + "google.api_core.path_template.transcode", + return_value={"method": "get", "uri": "/v1/test"}, + ): + transcoded, body, query_params = transcode_request(http_options, request) + assert query_params == {} + + +def test_transcode_with_required_fields_existing_key(): + http_options = [ + { + "method": "get", + "uri": "/v1/test", + } + ] + + request = descriptor_pb2.FieldDescriptorProto() + request.name = "custom-name" + + required_defaults = {"name": "default-name"} + + transcoded, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=required_defaults, + ) + + assert query_params["name"] == "custom-name" + + +def test_transcode_request_invalid_request(): + http_options = [{"method": "get", "uri": "/v1/test"}] + with pytest.raises(TypeError, match="request cannot be None"): + transcode_request(http_options, None) + + +def test_transcode_request_proto_plus_wrapper(): + http_options = [{"method": "get", "uri": "/v1/test/{name}"}] + mock_pb = descriptor_pb2.FieldDescriptorProto() + mock_pb.name = "proto-plus-field" + + mock_proto_plus = mock.Mock() + mock_proto_plus._pb = mock_pb + + transcoded, _, _ = transcode_request(http_options, mock_proto_plus) + assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_read_environment_variables(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "true", + "GOOGLE_API_USE_MTLS_ENDPOINT": "always", + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com", + }, + ): + use_cert, mtls_endpoint, universe_domain = read_environment_variables() + assert use_cert is True + assert mtls_endpoint == "always" + assert universe_domain == "foo.com" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): + with pytest.raises(MutualTLSChannelError): + read_environment_variables() diff --git a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_dep_service.py b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_dep_service.py new file mode 100644 index 000000000000..42091afea499 --- /dev/null +++ b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_dep_service.py @@ -0,0 +1,16867 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.network_services_v1beta1.services.dep_service import ( + DepServiceAsyncClient, + DepServiceClient, + pagers, + transports, +) +from google.cloud.network_services_v1beta1.types import common, dep + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert DepServiceClient._get_client_cert_source(None, False) is None + assert ( + DepServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + DepServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + DepServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + DepServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = DepServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = DepServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DepServiceClient, "grpc"), + (DepServiceAsyncClient, "grpc_asyncio"), + (DepServiceClient, "rest"), + ], +) +def test_dep_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.DepServiceGrpcTransport, "grpc"), + (transports.DepServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DepServiceRestTransport, "rest"), + ], +) +def test_dep_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DepServiceClient, "grpc"), + (DepServiceAsyncClient, "grpc_asyncio"), + (DepServiceClient, "rest"), + ], +) +def test_dep_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) + + +def test_dep_service_client_get_transport_class(): + transport = DepServiceClient.get_transport_class() + available_transports = [ + transports.DepServiceGrpcTransport, + transports.DepServiceRestTransport, + ] + assert transport in available_transports + + transport = DepServiceClient.get_transport_class("grpc") + assert transport == transports.DepServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), + ( + DepServiceAsyncClient, + transports.DepServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DepServiceClient, transports.DepServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + DepServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DepServiceClient), +) +@mock.patch.object( + DepServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DepServiceAsyncClient), +) +def test_dep_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DepServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DepServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", "true"), + ( + DepServiceAsyncClient, + transports.DepServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", "false"), + ( + DepServiceAsyncClient, + transports.DepServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (DepServiceClient, transports.DepServiceRestTransport, "rest", "true"), + (DepServiceClient, transports.DepServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + DepServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DepServiceClient), +) +@mock.patch.object( + DepServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DepServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dep_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [DepServiceClient, DepServiceAsyncClient]) +@mock.patch.object( + DepServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DepServiceClient) +) +@mock.patch.object( + DepServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DepServiceAsyncClient), +) +def test_dep_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [DepServiceClient, DepServiceAsyncClient]) +@mock.patch.object( + DepServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DepServiceClient), +) +@mock.patch.object( + DepServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DepServiceAsyncClient), +) +def test_dep_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DepServiceClient._DEFAULT_UNIVERSE + default_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = DepServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc"), + ( + DepServiceAsyncClient, + transports.DepServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DepServiceClient, transports.DepServiceRestTransport, "rest"), + ], +) +def test_dep_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", grpc_helpers), + ( + DepServiceAsyncClient, + transports.DepServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (DepServiceClient, transports.DepServiceRestTransport, "rest", None), + ], +) +def test_dep_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_dep_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.network_services_v1beta1.services.dep_service.transports.DepServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = DepServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (DepServiceClient, transports.DepServiceGrpcTransport, "grpc", grpc_helpers), + ( + DepServiceAsyncClient, + transports.DepServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_dep_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networkservices.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.ListLbTrafficExtensionsRequest(), + {}, + ], +) +def test_list_lb_traffic_extensions(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbTrafficExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.ListLbTrafficExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbTrafficExtensionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_lb_traffic_extensions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.ListLbTrafficExtensionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_lb_traffic_extensions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbTrafficExtensionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_lb_traffic_extensions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_lb_traffic_extensions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_lb_traffic_extensions + ] = mock_rpc + request = {} + client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_traffic_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_lb_traffic_extensions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_lb_traffic_extensions + ] = mock_rpc + + request = {} + await client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_lb_traffic_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.ListLbTrafficExtensionsRequest(), + {}, + ], +) +async def test_list_lb_traffic_extensions_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbTrafficExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.ListLbTrafficExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbTrafficExtensionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_lb_traffic_extensions_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbTrafficExtensionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + call.return_value = dep.ListLbTrafficExtensionsResponse() + client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbTrafficExtensionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbTrafficExtensionsResponse() + ) + await client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_lb_traffic_extensions_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbTrafficExtensionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_lb_traffic_extensions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_lb_traffic_extensions_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_lb_traffic_extensions( + dep.ListLbTrafficExtensionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbTrafficExtensionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbTrafficExtensionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_lb_traffic_extensions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_lb_traffic_extensions( + dep.ListLbTrafficExtensionsRequest(), + parent="parent_value", + ) + + +def test_list_lb_traffic_extensions_pager(transport_name: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token="abc", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token="def", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_lb_traffic_extensions( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbTrafficExtension) for i in results) + + +def test_list_lb_traffic_extensions_pages(transport_name: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token="abc", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token="def", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + RuntimeError, + ) + pages = list(client.list_lb_traffic_extensions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_async_pager(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token="abc", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token="def", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_lb_traffic_extensions( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dep.LbTrafficExtension) for i in responses) + + +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_async_pages(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token="abc", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token="def", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_lb_traffic_extensions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + dep.GetLbTrafficExtensionRequest(), + {}, + ], +) +def test_get_lb_traffic_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbTrafficExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + response = client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.GetLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbTrafficExtension) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.forwarding_rules == ["forwarding_rules_value"] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +def test_get_lb_traffic_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.GetLbTrafficExtensionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbTrafficExtensionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_lb_traffic_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_lb_traffic_extension + ] = mock_rpc + request = {} + client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_lb_traffic_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_lb_traffic_extension + ] = mock_rpc + + request = {} + await client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.GetLbTrafficExtensionRequest(), + {}, + ], +) +async def test_get_lb_traffic_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbTrafficExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + ) + response = await client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.GetLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbTrafficExtension) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.forwarding_rules == ["forwarding_rules_value"] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +def test_get_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbTrafficExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + call.return_value = dep.LbTrafficExtension() + client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbTrafficExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbTrafficExtension() + ) + await client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbTrafficExtension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_lb_traffic_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_lb_traffic_extension( + dep.GetLbTrafficExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbTrafficExtension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbTrafficExtension() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_lb_traffic_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_lb_traffic_extension( + dep.GetLbTrafficExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateLbTrafficExtensionRequest(), + {}, + ], +) +def test_create_lb_traffic_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.CreateLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_lb_traffic_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbTrafficExtensionRequest( + parent="parent_value", + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + assert args[0] == request_msg + + +def test_create_lb_traffic_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_lb_traffic_extension + ] = mock_rpc + request = {} + client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_lb_traffic_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_lb_traffic_extension + ] = mock_rpc + + request = {} + await client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateLbTrafficExtensionRequest(), + {}, + ], +) +async def test_create_lb_traffic_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.CreateLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbTrafficExtensionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbTrafficExtensionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_lb_traffic_extension( + parent="parent_value", + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].lb_traffic_extension + mock_val = dep.LbTrafficExtension(name="name_value") + assert arg == mock_val + arg = args[0].lb_traffic_extension_id + mock_val = "lb_traffic_extension_id_value" + assert arg == mock_val + + +def test_create_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_lb_traffic_extension( + dep.CreateLbTrafficExtensionRequest(), + parent="parent_value", + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_lb_traffic_extension( + parent="parent_value", + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].lb_traffic_extension + mock_val = dep.LbTrafficExtension(name="name_value") + assert arg == mock_val + arg = args[0].lb_traffic_extension_id + mock_val = "lb_traffic_extension_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_lb_traffic_extension( + dep.CreateLbTrafficExtensionRequest(), + parent="parent_value", + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateLbTrafficExtensionRequest(), + {}, + ], +) +def test_update_lb_traffic_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_lb_traffic_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.UpdateLbTrafficExtensionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbTrafficExtensionRequest() + assert args[0] == request_msg + + +def test_update_lb_traffic_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_lb_traffic_extension + ] = mock_rpc + request = {} + client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_lb_traffic_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_lb_traffic_extension + ] = mock_rpc + + request = {} + await client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateLbTrafficExtensionRequest(), + {}, + ], +) +async def test_update_lb_traffic_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbTrafficExtensionRequest() + + request.lb_traffic_extension.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "lb_traffic_extension.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbTrafficExtensionRequest() + + request.lb_traffic_extension.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "lb_traffic_extension.name=name_value", + ) in kw["metadata"] + + +def test_update_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_lb_traffic_extension( + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].lb_traffic_extension + mock_val = dep.LbTrafficExtension(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_lb_traffic_extension( + dep.UpdateLbTrafficExtensionRequest(), + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_lb_traffic_extension( + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].lb_traffic_extension + mock_val = dep.LbTrafficExtension(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_lb_traffic_extension( + dep.UpdateLbTrafficExtensionRequest(), + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteLbTrafficExtensionRequest(), + {}, + ], +) +def test_delete_lb_traffic_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_lb_traffic_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_lb_traffic_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbTrafficExtensionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_lb_traffic_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_lb_traffic_extension + ] = mock_rpc + request = {} + client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_lb_traffic_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_lb_traffic_extension + ] = mock_rpc + + request = {} + await client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteLbTrafficExtensionRequest(), + {}, + ], +) +async def test_delete_lb_traffic_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbTrafficExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_lb_traffic_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbTrafficExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbTrafficExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_lb_traffic_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_lb_traffic_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_lb_traffic_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_lb_traffic_extension( + dep.DeleteLbTrafficExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_lb_traffic_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_lb_traffic_extension( + dep.DeleteLbTrafficExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.ListLbRouteExtensionsRequest(), + {}, + ], +) +def test_list_lb_route_extensions(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbRouteExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.ListLbRouteExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbRouteExtensionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_lb_route_extensions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.ListLbRouteExtensionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_lb_route_extensions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbRouteExtensionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_lb_route_extensions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_lb_route_extensions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_lb_route_extensions + ] = mock_rpc + request = {} + client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_route_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_lb_route_extensions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_lb_route_extensions + ] = mock_rpc + + request = {} + await client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_lb_route_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.ListLbRouteExtensionsRequest(), + {}, + ], +) +async def test_list_lb_route_extensions_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbRouteExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.ListLbRouteExtensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbRouteExtensionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_lb_route_extensions_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbRouteExtensionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + call.return_value = dep.ListLbRouteExtensionsResponse() + client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListLbRouteExtensionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbRouteExtensionsResponse() + ) + await client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_lb_route_extensions_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbRouteExtensionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_lb_route_extensions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_lb_route_extensions_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_lb_route_extensions( + dep.ListLbRouteExtensionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListLbRouteExtensionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbRouteExtensionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_lb_route_extensions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_lb_route_extensions( + dep.ListLbRouteExtensionsRequest(), + parent="parent_value", + ) + + +def test_list_lb_route_extensions_pager(transport_name: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token="abc", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token="def", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_lb_route_extensions( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbRouteExtension) for i in results) + + +def test_list_lb_route_extensions_pages(transport_name: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token="abc", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token="def", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + RuntimeError, + ) + pages = list(client.list_lb_route_extensions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_async_pager(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token="abc", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token="def", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_lb_route_extensions( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dep.LbRouteExtension) for i in responses) + + +@pytest.mark.asyncio +async def test_list_lb_route_extensions_async_pages(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token="abc", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token="def", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_lb_route_extensions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + dep.GetLbRouteExtensionRequest(), + {}, + ], +) +def test_get_lb_route_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbRouteExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + response = client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.GetLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbRouteExtension) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.forwarding_rules == ["forwarding_rules_value"] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +def test_get_lb_route_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.GetLbRouteExtensionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbRouteExtensionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_lb_route_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_lb_route_extension] = ( + mock_rpc + ) + request = {} + client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_lb_route_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_lb_route_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_lb_route_extension + ] = mock_rpc + + request = {} + await client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.GetLbRouteExtensionRequest(), + {}, + ], +) +async def test_get_lb_route_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbRouteExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + ) + response = await client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.GetLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbRouteExtension) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.forwarding_rules == ["forwarding_rules_value"] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +def test_get_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbRouteExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + call.return_value = dep.LbRouteExtension() + client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetLbRouteExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbRouteExtension() + ) + await client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbRouteExtension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_lb_route_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_lb_route_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_lb_route_extension( + dep.GetLbRouteExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.LbRouteExtension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbRouteExtension() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_lb_route_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_lb_route_extension( + dep.GetLbRouteExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateLbRouteExtensionRequest(), + {}, + ], +) +def test_create_lb_route_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.CreateLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_lb_route_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbRouteExtensionRequest( + parent="parent_value", + lb_route_extension_id="lb_route_extension_id_value", + ) + assert args[0] == request_msg + + +def test_create_lb_route_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_lb_route_extension + ] = mock_rpc + request = {} + client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_lb_route_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_lb_route_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_lb_route_extension + ] = mock_rpc + + request = {} + await client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateLbRouteExtensionRequest(), + {}, + ], +) +async def test_create_lb_route_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.CreateLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbRouteExtensionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateLbRouteExtensionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_lb_route_extension( + parent="parent_value", + lb_route_extension=dep.LbRouteExtension(name="name_value"), + lb_route_extension_id="lb_route_extension_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].lb_route_extension + mock_val = dep.LbRouteExtension(name="name_value") + assert arg == mock_val + arg = args[0].lb_route_extension_id + mock_val = "lb_route_extension_id_value" + assert arg == mock_val + + +def test_create_lb_route_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_lb_route_extension( + dep.CreateLbRouteExtensionRequest(), + parent="parent_value", + lb_route_extension=dep.LbRouteExtension(name="name_value"), + lb_route_extension_id="lb_route_extension_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_lb_route_extension( + parent="parent_value", + lb_route_extension=dep.LbRouteExtension(name="name_value"), + lb_route_extension_id="lb_route_extension_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].lb_route_extension + mock_val = dep.LbRouteExtension(name="name_value") + assert arg == mock_val + arg = args[0].lb_route_extension_id + mock_val = "lb_route_extension_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_lb_route_extension( + dep.CreateLbRouteExtensionRequest(), + parent="parent_value", + lb_route_extension=dep.LbRouteExtension(name="name_value"), + lb_route_extension_id="lb_route_extension_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateLbRouteExtensionRequest(), + {}, + ], +) +def test_update_lb_route_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_lb_route_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.UpdateLbRouteExtensionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbRouteExtensionRequest() + assert args[0] == request_msg + + +def test_update_lb_route_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_lb_route_extension + ] = mock_rpc + request = {} + client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_lb_route_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_lb_route_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_lb_route_extension + ] = mock_rpc + + request = {} + await client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateLbRouteExtensionRequest(), + {}, + ], +) +async def test_update_lb_route_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.UpdateLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbRouteExtensionRequest() + + request.lb_route_extension.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "lb_route_extension.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateLbRouteExtensionRequest() + + request.lb_route_extension.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "lb_route_extension.name=name_value", + ) in kw["metadata"] + + +def test_update_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_lb_route_extension( + lb_route_extension=dep.LbRouteExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].lb_route_extension + mock_val = dep.LbRouteExtension(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_lb_route_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_lb_route_extension( + dep.UpdateLbRouteExtensionRequest(), + lb_route_extension=dep.LbRouteExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_lb_route_extension( + lb_route_extension=dep.LbRouteExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].lb_route_extension + mock_val = dep.LbRouteExtension(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_lb_route_extension( + dep.UpdateLbRouteExtensionRequest(), + lb_route_extension=dep.LbRouteExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteLbRouteExtensionRequest(), + {}, + ], +) +def test_delete_lb_route_extension(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_lb_route_extension_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.DeleteLbRouteExtensionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_lb_route_extension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbRouteExtensionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_lb_route_extension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_lb_route_extension + ] = mock_rpc + request = {} + client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_lb_route_extension_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_lb_route_extension + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_lb_route_extension + ] = mock_rpc + + request = {} + await client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteLbRouteExtensionRequest(), + {}, + ], +) +async def test_delete_lb_route_extension_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.DeleteLbRouteExtensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_lb_route_extension_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbRouteExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_lb_route_extension_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteLbRouteExtensionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_lb_route_extension_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_lb_route_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_lb_route_extension_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_lb_route_extension( + dep.DeleteLbRouteExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_lb_route_extension_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_lb_route_extension( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_lb_route_extension_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_lb_route_extension( + dep.DeleteLbRouteExtensionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.ListExtensionBindingsRequest(), + {}, + ], +) +def test_list_extension_bindings(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListExtensionBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_extension_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.ListExtensionBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExtensionBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_extension_bindings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.ListExtensionBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_extension_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListExtensionBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_extension_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_extension_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_extension_bindings + ] = mock_rpc + request = {} + client.list_extension_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_extension_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_extension_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_extension_bindings + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_extension_bindings + ] = mock_rpc + + request = {} + await client.list_extension_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_extension_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.ListExtensionBindingsRequest(), + {}, + ], +) +async def test_list_extension_bindings_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListExtensionBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_extension_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.ListExtensionBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExtensionBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_extension_bindings_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListExtensionBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + call.return_value = dep.ListExtensionBindingsResponse() + client.list_extension_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_extension_bindings_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.ListExtensionBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListExtensionBindingsResponse() + ) + await client.list_extension_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_extension_bindings_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListExtensionBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_extension_bindings( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_extension_bindings_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_extension_bindings( + dep.ListExtensionBindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_extension_bindings_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ListExtensionBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListExtensionBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_extension_bindings( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_extension_bindings_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_extension_bindings( + dep.ListExtensionBindingsRequest(), + parent="parent_value", + ) + + +def test_list_extension_bindings_pager(transport_name: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + next_page_token="abc", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[], + next_page_token="def", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + ], + next_page_token="ghi", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_extension_bindings(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.ExtensionBinding) for i in results) + + +def test_list_extension_bindings_pages(transport_name: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + next_page_token="abc", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[], + next_page_token="def", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + ], + next_page_token="ghi", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_extension_bindings(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_extension_bindings_async_pager(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + next_page_token="abc", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[], + next_page_token="def", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + ], + next_page_token="ghi", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_extension_bindings( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, dep.ExtensionBinding) for i in responses) + + +@pytest.mark.asyncio +async def test_list_extension_bindings_async_pages(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + next_page_token="abc", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[], + next_page_token="def", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + ], + next_page_token="ghi", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_extension_bindings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + dep.GetExtensionBindingRequest(), + {}, + ], +) +def test_get_extension_binding(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ExtensionBinding( + name="name_value", + description="description_value", + etag="etag_value", + producer_extension="producer_extension_value", + fail_open=True, + priority=898, + ) + response = client.get_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.GetExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.ExtensionBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.producer_extension == "producer_extension_value" + assert response.fail_open is True + assert response.priority == 898 + + +def test_get_extension_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.GetExtensionBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_extension_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetExtensionBindingRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_extension_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_extension_binding] = ( + mock_rpc + ) + request = {} + client.get_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_extension_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_extension_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_extension_binding + ] = mock_rpc + + request = {} + await client.get_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.GetExtensionBindingRequest(), + {}, + ], +) +async def test_get_extension_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ExtensionBinding( + name="name_value", + description="description_value", + etag="etag_value", + producer_extension="producer_extension_value", + fail_open=True, + priority=898, + ) + ) + response = await client.get_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.GetExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.ExtensionBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.producer_extension == "producer_extension_value" + assert response.fail_open is True + assert response.priority == 898 + + +def test_get_extension_binding_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetExtensionBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + call.return_value = dep.ExtensionBinding() + client.get_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_extension_binding_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.GetExtensionBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ExtensionBinding() + ) + await client.get_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_extension_binding_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ExtensionBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_extension_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_extension_binding_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_extension_binding( + dep.GetExtensionBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_extension_binding_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dep.ExtensionBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ExtensionBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_extension_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_extension_binding_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_extension_binding( + dep.GetExtensionBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateExtensionBindingRequest(), + {}, + ], +) +def test_create_extension_binding(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.CreateExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_extension_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.CreateExtensionBindingRequest( + parent="parent_value", + extension_binding_id="extension_binding_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_extension_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateExtensionBindingRequest( + parent="parent_value", + extension_binding_id="extension_binding_id_value", + ) + assert args[0] == request_msg + + +def test_create_extension_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_extension_binding + ] = mock_rpc + request = {} + client.create_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_extension_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_extension_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_extension_binding + ] = mock_rpc + + request = {} + await client.create_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateExtensionBindingRequest(), + {}, + ], +) +async def test_create_extension_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.CreateExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_extension_binding_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateExtensionBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_extension_binding_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.CreateExtensionBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_extension_binding_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_extension_binding( + parent="parent_value", + extension_binding=dep.ExtensionBinding(name="name_value"), + extension_binding_id="extension_binding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].extension_binding + mock_val = dep.ExtensionBinding(name="name_value") + assert arg == mock_val + arg = args[0].extension_binding_id + mock_val = "extension_binding_id_value" + assert arg == mock_val + + +def test_create_extension_binding_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_extension_binding( + dep.CreateExtensionBindingRequest(), + parent="parent_value", + extension_binding=dep.ExtensionBinding(name="name_value"), + extension_binding_id="extension_binding_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_extension_binding_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_extension_binding( + parent="parent_value", + extension_binding=dep.ExtensionBinding(name="name_value"), + extension_binding_id="extension_binding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].extension_binding + mock_val = dep.ExtensionBinding(name="name_value") + assert arg == mock_val + arg = args[0].extension_binding_id + mock_val = "extension_binding_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_extension_binding_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_extension_binding( + dep.CreateExtensionBindingRequest(), + parent="parent_value", + extension_binding=dep.ExtensionBinding(name="name_value"), + extension_binding_id="extension_binding_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateExtensionBindingRequest(), + {}, + ], +) +def test_update_extension_binding(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.UpdateExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_extension_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.UpdateExtensionBindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_extension_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateExtensionBindingRequest() + assert args[0] == request_msg + + +def test_update_extension_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_extension_binding + ] = mock_rpc + request = {} + client.update_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_extension_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_extension_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_extension_binding + ] = mock_rpc + + request = {} + await client.update_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateExtensionBindingRequest(), + {}, + ], +) +async def test_update_extension_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.UpdateExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_extension_binding_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateExtensionBindingRequest() + + request.extension_binding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "extension_binding.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_extension_binding_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.UpdateExtensionBindingRequest() + + request.extension_binding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "extension_binding.name=name_value", + ) in kw["metadata"] + + +def test_update_extension_binding_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_extension_binding( + extension_binding=dep.ExtensionBinding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].extension_binding + mock_val = dep.ExtensionBinding(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_extension_binding_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_extension_binding( + dep.UpdateExtensionBindingRequest(), + extension_binding=dep.ExtensionBinding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_extension_binding_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_extension_binding( + extension_binding=dep.ExtensionBinding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].extension_binding + mock_val = dep.ExtensionBinding(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_extension_binding_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_extension_binding( + dep.UpdateExtensionBindingRequest(), + extension_binding=dep.ExtensionBinding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteExtensionBindingRequest(), + {}, + ], +) +def test_delete_extension_binding(request_type, transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dep.DeleteExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_extension_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = dep.DeleteExtensionBindingRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_extension_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteExtensionBindingRequest( + name="name_value", + etag="etag_value", + ) + assert args[0] == request_msg + + +def test_delete_extension_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_extension_binding + ] = mock_rpc + request = {} + client.delete_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_extension_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_extension_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_extension_binding + ] = mock_rpc + + request = {} + await client.delete_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteExtensionBindingRequest(), + {}, + ], +) +async def test_delete_extension_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dep.DeleteExtensionBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_extension_binding_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteExtensionBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_extension_binding_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = dep.DeleteExtensionBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_extension_binding_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_extension_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_extension_binding_flattened_error(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_extension_binding( + dep.DeleteExtensionBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_extension_binding_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_extension_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_extension_binding_flattened_error_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_extension_binding( + dep.DeleteExtensionBindingRequest(), + name="name_value", + ) + + +def test_list_lb_traffic_extensions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_lb_traffic_extensions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_lb_traffic_extensions + ] = mock_rpc + + request = {} + client.list_lb_traffic_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_traffic_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_lb_traffic_extensions_rest_required_fields( + request_type=dep.ListLbTrafficExtensionsRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListLbTrafficExtensions, + "_BaseListLbTrafficExtensions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.ListLbTrafficExtensionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ListLbTrafficExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_lb_traffic_extensions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_lb_traffic_extensions_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ListLbTrafficExtensionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.ListLbTrafficExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_lb_traffic_extensions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/lbTrafficExtensions" + % client.transport._host, + args[1], + ) + + +def test_list_lb_traffic_extensions_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_lb_traffic_extensions( + dep.ListLbTrafficExtensionsRequest(), + parent="parent_value", + ) + + +def test_list_lb_traffic_extensions_rest_pager(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + next_page_token="abc", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[], + next_page_token="def", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbTrafficExtensionsResponse( + lb_traffic_extensions=[ + dep.LbTrafficExtension(), + dep.LbTrafficExtension(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + dep.ListLbTrafficExtensionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_lb_traffic_extensions(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbTrafficExtension) for i in results) + + pages = list(client.list_lb_traffic_extensions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_lb_traffic_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_lb_traffic_extension + ] = mock_rpc + + request = {} + client.get_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_lb_traffic_extension_rest_required_fields( + request_type=dep.GetLbTrafficExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetLbTrafficExtension, + "_BaseGetLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.LbTrafficExtension() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.LbTrafficExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_lb_traffic_extension(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.LbTrafficExtension() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.LbTrafficExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_lb_traffic_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/lbTrafficExtensions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_lb_traffic_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_lb_traffic_extension( + dep.GetLbTrafficExtensionRequest(), + name="name_value", + ) + + +def test_create_lb_traffic_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_lb_traffic_extension + ] = mock_rpc + + request = {} + client.create_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_lb_traffic_extension_rest_required_fields( + request_type=dep.CreateLbTrafficExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["lb_traffic_extension_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "lbTrafficExtensionId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateLbTrafficExtension, + "_BaseCreateLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "lbTrafficExtensionId" in jsonified_request + assert ( + jsonified_request["lbTrafficExtensionId"] + == request_init["lb_traffic_extension_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["lbTrafficExtensionId"] = "lb_traffic_extension_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "lbTrafficExtensionId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "lbTrafficExtensionId" in jsonified_request + assert jsonified_request["lbTrafficExtensionId"] == "lb_traffic_extension_id_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_lb_traffic_extension(request) + + expected_params = [ + ( + "lbTrafficExtensionId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_lb_traffic_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/lbTrafficExtensions" + % client.transport._host, + args[1], + ) + + +def test_create_lb_traffic_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_lb_traffic_extension( + dep.CreateLbTrafficExtensionRequest(), + parent="parent_value", + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + lb_traffic_extension_id="lb_traffic_extension_id_value", + ) + + +def test_update_lb_traffic_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_lb_traffic_extension + ] = mock_rpc + + request = {} + client.update_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_lb_traffic_extension_rest_required_fields( + request_type=dep.UpdateLbTrafficExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateLbTrafficExtension, + "_BaseUpdateLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_lb_traffic_extension(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "lb_traffic_extension": { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_lb_traffic_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{lb_traffic_extension.name=projects/*/locations/*/lbTrafficExtensions/*}" + % client.transport._host, + args[1], + ) + + +def test_update_lb_traffic_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_lb_traffic_extension( + dep.UpdateLbTrafficExtensionRequest(), + lb_traffic_extension=dep.LbTrafficExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_lb_traffic_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_lb_traffic_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_lb_traffic_extension + ] = mock_rpc + + request = {} + client.delete_lb_traffic_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_lb_traffic_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_lb_traffic_extension_rest_required_fields( + request_type=dep.DeleteLbTrafficExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteLbTrafficExtension, + "_BaseDeleteLbTrafficExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_lb_traffic_extension(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_lb_traffic_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_lb_traffic_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/lbTrafficExtensions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_lb_traffic_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_lb_traffic_extension( + dep.DeleteLbTrafficExtensionRequest(), + name="name_value", + ) + + +def test_list_lb_route_extensions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_lb_route_extensions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_lb_route_extensions + ] = mock_rpc + + request = {} + client.list_lb_route_extensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_lb_route_extensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_lb_route_extensions_rest_required_fields( + request_type=dep.ListLbRouteExtensionsRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListLbRouteExtensions, + "_BaseListLbRouteExtensions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.ListLbRouteExtensionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ListLbRouteExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_lb_route_extensions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_lb_route_extensions_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ListLbRouteExtensionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.ListLbRouteExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_lb_route_extensions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/lbRouteExtensions" + % client.transport._host, + args[1], + ) + + +def test_list_lb_route_extensions_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_lb_route_extensions( + dep.ListLbRouteExtensionsRequest(), + parent="parent_value", + ) + + +def test_list_lb_route_extensions_rest_pager(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + next_page_token="abc", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[], + next_page_token="def", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + ], + next_page_token="ghi", + ), + dep.ListLbRouteExtensionsResponse( + lb_route_extensions=[ + dep.LbRouteExtension(), + dep.LbRouteExtension(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dep.ListLbRouteExtensionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_lb_route_extensions(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.LbRouteExtension) for i in results) + + pages = list(client.list_lb_route_extensions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_lb_route_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_lb_route_extension] = ( + mock_rpc + ) + + request = {} + client.get_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_lb_route_extension_rest_required_fields( + request_type=dep.GetLbRouteExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetLbRouteExtension, + "_BaseGetLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.LbRouteExtension() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.LbRouteExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_lb_route_extension(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_lb_route_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.LbRouteExtension() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.LbRouteExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_lb_route_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/lbRouteExtensions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_lb_route_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_lb_route_extension( + dep.GetLbRouteExtensionRequest(), + name="name_value", + ) + + +def test_create_lb_route_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_lb_route_extension + ] = mock_rpc + + request = {} + client.create_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_lb_route_extension_rest_required_fields( + request_type=dep.CreateLbRouteExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["lb_route_extension_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "lbRouteExtensionId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateLbRouteExtension, + "_BaseCreateLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "lbRouteExtensionId" in jsonified_request + assert ( + jsonified_request["lbRouteExtensionId"] == request_init["lb_route_extension_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["lbRouteExtensionId"] = "lb_route_extension_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "lbRouteExtensionId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "lbRouteExtensionId" in jsonified_request + assert jsonified_request["lbRouteExtensionId"] == "lb_route_extension_id_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_lb_route_extension(request) + + expected_params = [ + ( + "lbRouteExtensionId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_lb_route_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + lb_route_extension=dep.LbRouteExtension(name="name_value"), + lb_route_extension_id="lb_route_extension_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_lb_route_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/lbRouteExtensions" + % client.transport._host, + args[1], + ) + + +def test_create_lb_route_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_lb_route_extension( + dep.CreateLbRouteExtensionRequest(), + parent="parent_value", + lb_route_extension=dep.LbRouteExtension(name="name_value"), + lb_route_extension_id="lb_route_extension_id_value", + ) + + +def test_update_lb_route_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_lb_route_extension + ] = mock_rpc + + request = {} + client.update_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_lb_route_extension_rest_required_fields( + request_type=dep.UpdateLbRouteExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateLbRouteExtension, + "_BaseUpdateLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_lb_route_extension(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_lb_route_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "lb_route_extension": { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + lb_route_extension=dep.LbRouteExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_lb_route_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{lb_route_extension.name=projects/*/locations/*/lbRouteExtensions/*}" + % client.transport._host, + args[1], + ) + + +def test_update_lb_route_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_lb_route_extension( + dep.UpdateLbRouteExtensionRequest(), + lb_route_extension=dep.LbRouteExtension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_lb_route_extension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_lb_route_extension + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_lb_route_extension + ] = mock_rpc + + request = {} + client.delete_lb_route_extension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_lb_route_extension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_lb_route_extension_rest_required_fields( + request_type=dep.DeleteLbRouteExtensionRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteLbRouteExtension, + "_BaseDeleteLbRouteExtension__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_lb_route_extension(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_lb_route_extension_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_lb_route_extension(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/lbRouteExtensions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_lb_route_extension_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_lb_route_extension( + dep.DeleteLbRouteExtensionRequest(), + name="name_value", + ) + + +def test_list_extension_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_extension_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_extension_bindings + ] = mock_rpc + + request = {} + client.list_extension_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_extension_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_extension_bindings_rest_required_fields( + request_type=dep.ListExtensionBindingsRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListExtensionBindings, + "_BaseListExtensionBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.ListExtensionBindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ListExtensionBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_extension_bindings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_extension_bindings_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ListExtensionBindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.ListExtensionBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_extension_bindings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/extensionBindings" + % client.transport._host, + args[1], + ) + + +def test_list_extension_bindings_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_extension_bindings( + dep.ListExtensionBindingsRequest(), + parent="parent_value", + ) + + +def test_list_extension_bindings_rest_pager(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + next_page_token="abc", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[], + next_page_token="def", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + ], + next_page_token="ghi", + ), + dep.ListExtensionBindingsResponse( + extension_bindings=[ + dep.ExtensionBinding(), + dep.ExtensionBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dep.ListExtensionBindingsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_extension_bindings(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dep.ExtensionBinding) for i in results) + + pages = list(client.list_extension_bindings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_extension_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_extension_binding] = ( + mock_rpc + ) + + request = {} + client.get_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_extension_binding_rest_required_fields( + request_type=dep.GetExtensionBindingRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetExtensionBinding, + "_BaseGetExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dep.ExtensionBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ExtensionBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_extension_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_extension_binding_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ExtensionBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = dep.ExtensionBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_extension_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/extensionBindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_extension_binding_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_extension_binding( + dep.GetExtensionBindingRequest(), + name="name_value", + ) + + +def test_create_extension_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_extension_binding + ] = mock_rpc + + request = {} + client.create_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_extension_binding_rest_required_fields( + request_type=dep.CreateExtensionBindingRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["extension_binding_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "extensionBindingId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateExtensionBinding, + "_BaseCreateExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "extensionBindingId" in jsonified_request + assert ( + jsonified_request["extensionBindingId"] == request_init["extension_binding_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["extensionBindingId"] = "extension_binding_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("extensionBindingId",)) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "extensionBindingId" in jsonified_request + assert jsonified_request["extensionBindingId"] == "extension_binding_id_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_extension_binding(request) + + expected_params = [ + ( + "extensionBindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_extension_binding_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + extension_binding=dep.ExtensionBinding(name="name_value"), + extension_binding_id="extension_binding_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_extension_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/extensionBindings" + % client.transport._host, + args[1], + ) + + +def test_create_extension_binding_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_extension_binding( + dep.CreateExtensionBindingRequest(), + parent="parent_value", + extension_binding=dep.ExtensionBinding(name="name_value"), + extension_binding_id="extension_binding_id_value", + ) + + +def test_update_extension_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_extension_binding + ] = mock_rpc + + request = {} + client.update_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_extension_binding_rest_required_fields( + request_type=dep.UpdateExtensionBindingRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateExtensionBinding, + "_BaseUpdateExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_extension_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_extension_binding_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "extension_binding": { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + extension_binding=dep.ExtensionBinding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_extension_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{extension_binding.name=projects/*/locations/*/extensionBindings/*}" + % client.transport._host, + args[1], + ) + + +def test_update_extension_binding_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_extension_binding( + dep.UpdateExtensionBindingRequest(), + extension_binding=dep.ExtensionBinding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_extension_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_extension_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_extension_binding + ] = mock_rpc + + request = {} + client.delete_extension_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_extension_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_extension_binding_rest_required_fields( + request_type=dep.DeleteExtensionBindingRequest, +): + transport_class = transports.DepServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteExtensionBinding, + "_BaseDeleteExtensionBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_extension_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_extension_binding_rest_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_extension_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/extensionBindings/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_extension_binding_rest_flattened_error(transport: str = "rest"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_extension_binding( + dep.DeleteExtensionBindingRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DepServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DepServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DepServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DepServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DepServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DepServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DepServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DepServiceGrpcTransport, + transports.DepServiceGrpcAsyncIOTransport, + transports.DepServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = DepServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_lb_traffic_extensions_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + call.return_value = dep.ListLbTrafficExtensionsResponse() + client.list_lb_traffic_extensions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbTrafficExtensionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_lb_traffic_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + call.return_value = dep.LbTrafficExtension() + client.get_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_lb_traffic_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_lb_traffic_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_lb_traffic_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_lb_route_extensions_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + call.return_value = dep.ListLbRouteExtensionsResponse() + client.list_lb_route_extensions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbRouteExtensionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_lb_route_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + call.return_value = dep.LbRouteExtension() + client.get_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_lb_route_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_lb_route_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_lb_route_extension_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_extension_bindings_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + call.return_value = dep.ListExtensionBindingsResponse() + client.list_extension_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListExtensionBindingsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_extension_binding_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + call.return_value = dep.ExtensionBinding() + client.get_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_extension_binding_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_extension_binding_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_extension_binding_empty_call_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteExtensionBindingRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = DepServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_lb_traffic_extensions_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbTrafficExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_lb_traffic_extensions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbTrafficExtensionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_lb_traffic_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbTrafficExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + ) + await client.get_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_lb_traffic_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_lb_traffic_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_lb_traffic_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_lb_route_extensions_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListLbRouteExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_lb_route_extensions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbRouteExtensionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_lb_route_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.LbRouteExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + ) + await client.get_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_lb_route_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_lb_route_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_lb_route_extension_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_extension_bindings_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ListExtensionBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_extension_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListExtensionBindingsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_extension_binding_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dep.ExtensionBinding( + name="name_value", + description="description_value", + etag="etag_value", + producer_extension="producer_extension_value", + fail_open=True, + priority=898, + ) + ) + await client.get_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_extension_binding_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_extension_binding_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_extension_binding_empty_call_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteExtensionBindingRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = DepServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_lb_traffic_extensions_rest_bad_request( + request_type=dep.ListLbTrafficExtensionsRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_lb_traffic_extensions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.ListLbTrafficExtensionsRequest, + dict, + ], +) +def test_list_lb_traffic_extensions_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ListLbTrafficExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ListLbTrafficExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_lb_traffic_extensions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbTrafficExtensionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_lb_traffic_extensions_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DepServiceRestInterceptor, "post_list_lb_traffic_extensions" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_list_lb_traffic_extensions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_list_lb_traffic_extensions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.ListLbTrafficExtensionsRequest.pb( + dep.ListLbTrafficExtensionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = dep.ListLbTrafficExtensionsResponse.to_json( + dep.ListLbTrafficExtensionsResponse() + ) + req.return_value.content = return_value + + request = dep.ListLbTrafficExtensionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.ListLbTrafficExtensionsResponse() + post_with_metadata.return_value = ( + dep.ListLbTrafficExtensionsResponse(), + metadata, + ) + + client.list_lb_traffic_extensions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_lb_traffic_extension_rest_bad_request( + request_type=dep.GetLbTrafficExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_lb_traffic_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.GetLbTrafficExtensionRequest, + dict, + ], +) +def test_get_lb_traffic_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.LbTrafficExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.LbTrafficExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbTrafficExtension) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.forwarding_rules == ["forwarding_rules_value"] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DepServiceRestInterceptor, "post_get_lb_traffic_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_get_lb_traffic_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_get_lb_traffic_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.GetLbTrafficExtensionRequest.pb( + dep.GetLbTrafficExtensionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = dep.LbTrafficExtension.to_json(dep.LbTrafficExtension()) + req.return_value.content = return_value + + request = dep.GetLbTrafficExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.LbTrafficExtension() + post_with_metadata.return_value = dep.LbTrafficExtension(), metadata + + client.get_lb_traffic_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_lb_traffic_extension_rest_bad_request( + request_type=dep.CreateLbTrafficExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_lb_traffic_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateLbTrafficExtensionRequest, + dict, + ], +) +def test_create_lb_traffic_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["lb_traffic_extension"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "forwarding_rules": ["forwarding_rules_value1", "forwarding_rules_value2"], + "extension_chains": [ + { + "name": "name_value", + "match_condition": {"cel_expression": "cel_expression_value"}, + "extensions": [ + { + "name": "name_value", + "authority": "authority_value", + "service": "service_value", + "supported_events": [1], + "timeout": {"seconds": 751, "nanos": 543}, + "fail_open": True, + "forward_headers": [ + "forward_headers_value1", + "forward_headers_value2", + ], + } + ], + } + ], + "load_balancing_scheme": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = dep.CreateLbTrafficExtensionRequest.meta.fields["lb_traffic_extension"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "lb_traffic_extension" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["lb_traffic_extension"][field])): + del request_init["lb_traffic_extension"][field][i][subfield] + else: + del request_init["lb_traffic_extension"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_create_lb_traffic_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_create_lb_traffic_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_create_lb_traffic_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.CreateLbTrafficExtensionRequest.pb( + dep.CreateLbTrafficExtensionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.CreateLbTrafficExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_lb_traffic_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_lb_traffic_extension_rest_bad_request( + request_type=dep.UpdateLbTrafficExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "lb_traffic_extension": { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_lb_traffic_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateLbTrafficExtensionRequest, + dict, + ], +) +def test_update_lb_traffic_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "lb_traffic_extension": { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + } + request_init["lb_traffic_extension"] = { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "forwarding_rules": ["forwarding_rules_value1", "forwarding_rules_value2"], + "extension_chains": [ + { + "name": "name_value", + "match_condition": {"cel_expression": "cel_expression_value"}, + "extensions": [ + { + "name": "name_value", + "authority": "authority_value", + "service": "service_value", + "supported_events": [1], + "timeout": {"seconds": 751, "nanos": 543}, + "fail_open": True, + "forward_headers": [ + "forward_headers_value1", + "forward_headers_value2", + ], + } + ], + } + ], + "load_balancing_scheme": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = dep.UpdateLbTrafficExtensionRequest.meta.fields["lb_traffic_extension"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "lb_traffic_extension" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["lb_traffic_extension"][field])): + del request_init["lb_traffic_extension"][field][i][subfield] + else: + del request_init["lb_traffic_extension"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_update_lb_traffic_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_update_lb_traffic_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_update_lb_traffic_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.UpdateLbTrafficExtensionRequest.pb( + dep.UpdateLbTrafficExtensionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.UpdateLbTrafficExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_lb_traffic_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_lb_traffic_extension_rest_bad_request( + request_type=dep.DeleteLbTrafficExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_lb_traffic_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteLbTrafficExtensionRequest, + dict, + ], +) +def test_delete_lb_traffic_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbTrafficExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_lb_traffic_extension(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_lb_traffic_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_delete_lb_traffic_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_delete_lb_traffic_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_delete_lb_traffic_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.DeleteLbTrafficExtensionRequest.pb( + dep.DeleteLbTrafficExtensionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.DeleteLbTrafficExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_lb_traffic_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_lb_route_extensions_rest_bad_request( + request_type=dep.ListLbRouteExtensionsRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_lb_route_extensions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.ListLbRouteExtensionsRequest, + dict, + ], +) +def test_list_lb_route_extensions_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ListLbRouteExtensionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ListLbRouteExtensionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_lb_route_extensions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLbRouteExtensionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_lb_route_extensions_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DepServiceRestInterceptor, "post_list_lb_route_extensions" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_list_lb_route_extensions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_list_lb_route_extensions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.ListLbRouteExtensionsRequest.pb( + dep.ListLbRouteExtensionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = dep.ListLbRouteExtensionsResponse.to_json( + dep.ListLbRouteExtensionsResponse() + ) + req.return_value.content = return_value + + request = dep.ListLbRouteExtensionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.ListLbRouteExtensionsResponse() + post_with_metadata.return_value = dep.ListLbRouteExtensionsResponse(), metadata + + client.list_lb_route_extensions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_lb_route_extension_rest_bad_request( + request_type=dep.GetLbRouteExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_lb_route_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.GetLbRouteExtensionRequest, + dict, + ], +) +def test_get_lb_route_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.LbRouteExtension( + name="name_value", + description="description_value", + forwarding_rules=["forwarding_rules_value"], + load_balancing_scheme=dep.LoadBalancingScheme.INTERNAL_MANAGED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.LbRouteExtension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_lb_route_extension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.LbRouteExtension) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.forwarding_rules == ["forwarding_rules_value"] + assert response.load_balancing_scheme == dep.LoadBalancingScheme.INTERNAL_MANAGED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DepServiceRestInterceptor, "post_get_lb_route_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_get_lb_route_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_get_lb_route_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.GetLbRouteExtensionRequest.pb(dep.GetLbRouteExtensionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = dep.LbRouteExtension.to_json(dep.LbRouteExtension()) + req.return_value.content = return_value + + request = dep.GetLbRouteExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.LbRouteExtension() + post_with_metadata.return_value = dep.LbRouteExtension(), metadata + + client.get_lb_route_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_lb_route_extension_rest_bad_request( + request_type=dep.CreateLbRouteExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_lb_route_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateLbRouteExtensionRequest, + dict, + ], +) +def test_create_lb_route_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["lb_route_extension"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "forwarding_rules": ["forwarding_rules_value1", "forwarding_rules_value2"], + "extension_chains": [ + { + "name": "name_value", + "match_condition": {"cel_expression": "cel_expression_value"}, + "extensions": [ + { + "name": "name_value", + "authority": "authority_value", + "service": "service_value", + "supported_events": [1], + "timeout": {"seconds": 751, "nanos": 543}, + "fail_open": True, + "forward_headers": [ + "forward_headers_value1", + "forward_headers_value2", + ], + } + ], + } + ], + "load_balancing_scheme": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = dep.CreateLbRouteExtensionRequest.meta.fields["lb_route_extension"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["lb_route_extension"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["lb_route_extension"][field])): + del request_init["lb_route_extension"][field][i][subfield] + else: + del request_init["lb_route_extension"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_lb_route_extension(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_create_lb_route_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_create_lb_route_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_create_lb_route_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.CreateLbRouteExtensionRequest.pb( + dep.CreateLbRouteExtensionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.CreateLbRouteExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_lb_route_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_lb_route_extension_rest_bad_request( + request_type=dep.UpdateLbRouteExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "lb_route_extension": { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_lb_route_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateLbRouteExtensionRequest, + dict, + ], +) +def test_update_lb_route_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "lb_route_extension": { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + } + request_init["lb_route_extension"] = { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "forwarding_rules": ["forwarding_rules_value1", "forwarding_rules_value2"], + "extension_chains": [ + { + "name": "name_value", + "match_condition": {"cel_expression": "cel_expression_value"}, + "extensions": [ + { + "name": "name_value", + "authority": "authority_value", + "service": "service_value", + "supported_events": [1], + "timeout": {"seconds": 751, "nanos": 543}, + "fail_open": True, + "forward_headers": [ + "forward_headers_value1", + "forward_headers_value2", + ], + } + ], + } + ], + "load_balancing_scheme": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = dep.UpdateLbRouteExtensionRequest.meta.fields["lb_route_extension"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["lb_route_extension"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["lb_route_extension"][field])): + del request_init["lb_route_extension"][field][i][subfield] + else: + del request_init["lb_route_extension"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_lb_route_extension(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_update_lb_route_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_update_lb_route_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_update_lb_route_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.UpdateLbRouteExtensionRequest.pb( + dep.UpdateLbRouteExtensionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.UpdateLbRouteExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_lb_route_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_lb_route_extension_rest_bad_request( + request_type=dep.DeleteLbRouteExtensionRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_lb_route_extension(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteLbRouteExtensionRequest, + dict, + ], +) +def test_delete_lb_route_extension_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/lbRouteExtensions/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_lb_route_extension(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_lb_route_extension_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_delete_lb_route_extension" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_delete_lb_route_extension_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_delete_lb_route_extension" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.DeleteLbRouteExtensionRequest.pb( + dep.DeleteLbRouteExtensionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.DeleteLbRouteExtensionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_lb_route_extension( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_extension_bindings_rest_bad_request( + request_type=dep.ListExtensionBindingsRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_extension_bindings(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.ListExtensionBindingsRequest, + dict, + ], +) +def test_list_extension_bindings_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ListExtensionBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ListExtensionBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_extension_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExtensionBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_extension_bindings_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DepServiceRestInterceptor, "post_list_extension_bindings" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_list_extension_bindings_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_list_extension_bindings" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.ListExtensionBindingsRequest.pb( + dep.ListExtensionBindingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = dep.ListExtensionBindingsResponse.to_json( + dep.ListExtensionBindingsResponse() + ) + req.return_value.content = return_value + + request = dep.ListExtensionBindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.ListExtensionBindingsResponse() + post_with_metadata.return_value = dep.ListExtensionBindingsResponse(), metadata + + client.list_extension_bindings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_extension_binding_rest_bad_request( + request_type=dep.GetExtensionBindingRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_extension_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.GetExtensionBindingRequest, + dict, + ], +) +def test_get_extension_binding_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dep.ExtensionBinding( + name="name_value", + description="description_value", + etag="etag_value", + producer_extension="producer_extension_value", + fail_open=True, + priority=898, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = dep.ExtensionBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_extension_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dep.ExtensionBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.producer_extension == "producer_extension_value" + assert response.fail_open is True + assert response.priority == 898 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_extension_binding_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DepServiceRestInterceptor, "post_get_extension_binding" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_get_extension_binding_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_get_extension_binding" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.GetExtensionBindingRequest.pb(dep.GetExtensionBindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = dep.ExtensionBinding.to_json(dep.ExtensionBinding()) + req.return_value.content = return_value + + request = dep.GetExtensionBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dep.ExtensionBinding() + post_with_metadata.return_value = dep.ExtensionBinding(), metadata + + client.get_extension_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_extension_binding_rest_bad_request( + request_type=dep.CreateExtensionBindingRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_extension_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.CreateExtensionBindingRequest, + dict, + ], +) +def test_create_extension_binding_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["extension_binding"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "etag": "etag_value", + "producer_extension": "producer_extension_value", + "target": { + "resources": ["resources_value1", "resources_value2"], + "scope": {"parent": "parent_value", "resource_types": [1]}, + }, + "match_conditions": [ + { + "to": { + "destination": { + "header_set": { + "headers": [ + { + "name": "name_value", + "value": { + "exact": "exact_value", + "prefix": "prefix_value", + "suffix": "suffix_value", + "contains": "contains_value", + "ignore_case": True, + }, + } + ] + }, + "resources": {}, + "hosts": {}, + "paths": {}, + }, + "not_destination": {}, + } + } + ], + "fail_open": True, + "producer_metadata": {}, + "priority": 898, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = dep.CreateExtensionBindingRequest.meta.fields["extension_binding"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["extension_binding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["extension_binding"][field])): + del request_init["extension_binding"][field][i][subfield] + else: + del request_init["extension_binding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_extension_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_extension_binding_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_create_extension_binding" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_create_extension_binding_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_create_extension_binding" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.CreateExtensionBindingRequest.pb( + dep.CreateExtensionBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.CreateExtensionBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_extension_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_extension_binding_rest_bad_request( + request_type=dep.UpdateExtensionBindingRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "extension_binding": { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_extension_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.UpdateExtensionBindingRequest, + dict, + ], +) +def test_update_extension_binding_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "extension_binding": { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + } + request_init["extension_binding"] = { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "etag": "etag_value", + "producer_extension": "producer_extension_value", + "target": { + "resources": ["resources_value1", "resources_value2"], + "scope": {"parent": "parent_value", "resource_types": [1]}, + }, + "match_conditions": [ + { + "to": { + "destination": { + "header_set": { + "headers": [ + { + "name": "name_value", + "value": { + "exact": "exact_value", + "prefix": "prefix_value", + "suffix": "suffix_value", + "contains": "contains_value", + "ignore_case": True, + }, + } + ] + }, + "resources": {}, + "hosts": {}, + "paths": {}, + }, + "not_destination": {}, + } + } + ], + "fail_open": True, + "producer_metadata": {}, + "priority": 898, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = dep.UpdateExtensionBindingRequest.meta.fields["extension_binding"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["extension_binding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["extension_binding"][field])): + del request_init["extension_binding"][field][i][subfield] + else: + del request_init["extension_binding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_extension_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_extension_binding_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_update_extension_binding" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_update_extension_binding_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_update_extension_binding" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.UpdateExtensionBindingRequest.pb( + dep.UpdateExtensionBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.UpdateExtensionBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_extension_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_extension_binding_rest_bad_request( + request_type=dep.DeleteExtensionBindingRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_extension_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dep.DeleteExtensionBindingRequest, + dict, + ], +) +def test_delete_extension_binding_rest_call_success(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/extensionBindings/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_extension_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_extension_binding_rest_interceptors(null_interceptor): + transport = transports.DepServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DepServiceRestInterceptor(), + ) + client = DepServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.DepServiceRestInterceptor, "post_delete_extension_binding" + ) as post, + mock.patch.object( + transports.DepServiceRestInterceptor, + "post_delete_extension_binding_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DepServiceRestInterceptor, "pre_delete_extension_binding" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dep.DeleteExtensionBindingRequest.pb( + dep.DeleteExtensionBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = dep.DeleteExtensionBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_extension_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/endpointPolicies/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/endpointPolicies/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/endpointPolicies/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_lb_traffic_extensions_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_traffic_extensions), "__call__" + ) as call: + client.list_lb_traffic_extensions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbTrafficExtensionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_lb_traffic_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_traffic_extension), "__call__" + ) as call: + client.get_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_lb_traffic_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_traffic_extension), "__call__" + ) as call: + client.create_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_lb_traffic_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_traffic_extension), "__call__" + ) as call: + client.update_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_lb_traffic_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_traffic_extension), "__call__" + ) as call: + client.delete_lb_traffic_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbTrafficExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_lb_route_extensions_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_lb_route_extensions), "__call__" + ) as call: + client.list_lb_route_extensions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListLbRouteExtensionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_lb_route_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_lb_route_extension), "__call__" + ) as call: + client.get_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_lb_route_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_lb_route_extension), "__call__" + ) as call: + client.create_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_lb_route_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_lb_route_extension), "__call__" + ) as call: + client.update_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_lb_route_extension_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_lb_route_extension), "__call__" + ) as call: + client.delete_lb_route_extension(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteLbRouteExtensionRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_extension_bindings_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_extension_bindings), "__call__" + ) as call: + client.list_extension_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.ListExtensionBindingsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_extension_binding_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_extension_binding), "__call__" + ) as call: + client.get_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.GetExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_extension_binding_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_extension_binding), "__call__" + ) as call: + client.create_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.CreateExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_extension_binding_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_extension_binding), "__call__" + ) as call: + client.update_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.UpdateExtensionBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_extension_binding_empty_call_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_extension_binding), "__call__" + ) as call: + client.delete_extension_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dep.DeleteExtensionBindingRequest() + assert args[0] == request_msg + + +def test_dep_service_rest_lro_client(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DepServiceGrpcTransport, + ) + + +def test_dep_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DepServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_dep_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.network_services_v1beta1.services.dep_service.transports.DepServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DepServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_lb_traffic_extensions", + "get_lb_traffic_extension", + "create_lb_traffic_extension", + "update_lb_traffic_extension", + "delete_lb_traffic_extension", + "list_lb_route_extensions", + "get_lb_route_extension", + "create_lb_route_extension", + "update_lb_route_extension", + "delete_lb_route_extension", + "list_extension_bindings", + "get_extension_binding", + "create_extension_binding", + "update_extension_binding", + "delete_extension_binding", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_dep_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.network_services_v1beta1.services.dep_service.transports.DepServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DepServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_dep_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.network_services_v1beta1.services.dep_service.transports.DepServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DepServiceTransport() + adc.assert_called_once() + + +def test_dep_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DepServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DepServiceGrpcTransport, + transports.DepServiceGrpcAsyncIOTransport, + ], +) +def test_dep_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DepServiceGrpcTransport, + transports.DepServiceGrpcAsyncIOTransport, + transports.DepServiceRestTransport, + ], +) +def test_dep_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DepServiceGrpcTransport, grpc_helpers), + (transports.DepServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_dep_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "networkservices.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport], +) +def test_dep_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_dep_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DepServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_dep_service_host_no_port(transport_name): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networkservices.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_dep_service_host_with_port(transport_name): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networkservices.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networkservices.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_dep_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DepServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DepServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_lb_traffic_extensions._session + session2 = client2.transport.list_lb_traffic_extensions._session + assert session1 != session2 + session1 = client1.transport.get_lb_traffic_extension._session + session2 = client2.transport.get_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.create_lb_traffic_extension._session + session2 = client2.transport.create_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.update_lb_traffic_extension._session + session2 = client2.transport.update_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.delete_lb_traffic_extension._session + session2 = client2.transport.delete_lb_traffic_extension._session + assert session1 != session2 + session1 = client1.transport.list_lb_route_extensions._session + session2 = client2.transport.list_lb_route_extensions._session + assert session1 != session2 + session1 = client1.transport.get_lb_route_extension._session + session2 = client2.transport.get_lb_route_extension._session + assert session1 != session2 + session1 = client1.transport.create_lb_route_extension._session + session2 = client2.transport.create_lb_route_extension._session + assert session1 != session2 + session1 = client1.transport.update_lb_route_extension._session + session2 = client2.transport.update_lb_route_extension._session + assert session1 != session2 + session1 = client1.transport.delete_lb_route_extension._session + session2 = client2.transport.delete_lb_route_extension._session + assert session1 != session2 + session1 = client1.transport.list_extension_bindings._session + session2 = client2.transport.list_extension_bindings._session + assert session1 != session2 + session1 = client1.transport.get_extension_binding._session + session2 = client2.transport.get_extension_binding._session + assert session1 != session2 + session1 = client1.transport.create_extension_binding._session + session2 = client2.transport.create_extension_binding._session + assert session1 != session2 + session1 = client1.transport.update_extension_binding._session + session2 = client2.transport.update_extension_binding._session + assert session1 != session2 + session1 = client1.transport.delete_extension_binding._session + session2 = client2.transport.delete_extension_binding._session + assert session1 != session2 + + +def test_dep_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DepServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_dep_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DepServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport], +) +def test_dep_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.DepServiceGrpcTransport, transports.DepServiceGrpcAsyncIOTransport], +) +def test_dep_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_dep_service_grpc_lro_client(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_dep_service_grpc_lro_async_client(): + client = DepServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_extension_binding_path(): + project = "squid" + location = "clam" + extension_binding = "whelk" + expected = "projects/{project}/locations/{location}/extensionBindings/{extension_binding}".format( + project=project, + location=location, + extension_binding=extension_binding, + ) + actual = DepServiceClient.extension_binding_path( + project, location, extension_binding + ) + assert expected == actual + + +def test_parse_extension_binding_path(): + expected = { + "project": "octopus", + "location": "oyster", + "extension_binding": "nudibranch", + } + path = DepServiceClient.extension_binding_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_extension_binding_path(path) + assert expected == actual + + +def test_lb_route_extension_path(): + project = "cuttlefish" + location = "mussel" + lb_route_extension = "winkle" + expected = "projects/{project}/locations/{location}/lbRouteExtensions/{lb_route_extension}".format( + project=project, + location=location, + lb_route_extension=lb_route_extension, + ) + actual = DepServiceClient.lb_route_extension_path( + project, location, lb_route_extension + ) + assert expected == actual + + +def test_parse_lb_route_extension_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "lb_route_extension": "abalone", + } + path = DepServiceClient.lb_route_extension_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_lb_route_extension_path(path) + assert expected == actual + + +def test_lb_traffic_extension_path(): + project = "squid" + location = "clam" + lb_traffic_extension = "whelk" + expected = "projects/{project}/locations/{location}/lbTrafficExtensions/{lb_traffic_extension}".format( + project=project, + location=location, + lb_traffic_extension=lb_traffic_extension, + ) + actual = DepServiceClient.lb_traffic_extension_path( + project, location, lb_traffic_extension + ) + assert expected == actual + + +def test_parse_lb_traffic_extension_path(): + expected = { + "project": "octopus", + "location": "oyster", + "lb_traffic_extension": "nudibranch", + } + path = DepServiceClient.lb_traffic_extension_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_lb_traffic_extension_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = DepServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DepServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = DepServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DepServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = DepServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DepServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = DepServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DepServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = DepServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DepServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DepServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.DepServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.DepServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = DepServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = DepServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = DepServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = DepServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = DepServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (DepServiceClient, transports.DepServiceGrpcTransport), + (DepServiceAsyncClient, transports.DepServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_network_services.py b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_network_services.py new file mode 100644 index 000000000000..6327e13df0ca --- /dev/null +++ b/packages/google-cloud-network-services/tests/unit/gapic/network_services_v1beta1/test_network_services.py @@ -0,0 +1,8490 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.network_services_v1beta1.services.network_services import ( + NetworkServicesAsyncClient, + NetworkServicesClient, + pagers, + transports, +) +from google.cloud.network_services_v1beta1.types import common, endpoint_policy +from google.cloud.network_services_v1beta1.types import ( + endpoint_policy as gcn_endpoint_policy, +) + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert NetworkServicesClient._get_client_cert_source(None, False) is None + assert ( + NetworkServicesClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + NetworkServicesClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + NetworkServicesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + NetworkServicesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = NetworkServicesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = NetworkServicesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (NetworkServicesClient, "grpc"), + (NetworkServicesAsyncClient, "grpc_asyncio"), + (NetworkServicesClient, "rest"), + ], +) +def test_network_services_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.NetworkServicesGrpcTransport, "grpc"), + (transports.NetworkServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.NetworkServicesRestTransport, "rest"), + ], +) +def test_network_services_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (NetworkServicesClient, "grpc"), + (NetworkServicesAsyncClient, "grpc_asyncio"), + (NetworkServicesClient, "rest"), + ], +) +def test_network_services_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) + + +def test_network_services_client_get_transport_class(): + transport = NetworkServicesClient.get_transport_class() + available_transports = [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesRestTransport, + ] + assert transport in available_transports + + transport = NetworkServicesClient.get_transport_class("grpc") + assert transport == transports.NetworkServicesGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), + ( + NetworkServicesAsyncClient, + transports.NetworkServicesGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), + ], +) +@mock.patch.object( + NetworkServicesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NetworkServicesClient), +) +@mock.patch.object( + NetworkServicesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NetworkServicesAsyncClient), +) +def test_network_services_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(NetworkServicesClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(NetworkServicesClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + NetworkServicesClient, + transports.NetworkServicesGrpcTransport, + "grpc", + "true", + ), + ( + NetworkServicesAsyncClient, + transports.NetworkServicesGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + NetworkServicesClient, + transports.NetworkServicesGrpcTransport, + "grpc", + "false", + ), + ( + NetworkServicesAsyncClient, + transports.NetworkServicesGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + NetworkServicesClient, + transports.NetworkServicesRestTransport, + "rest", + "true", + ), + ( + NetworkServicesClient, + transports.NetworkServicesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + NetworkServicesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NetworkServicesClient), +) +@mock.patch.object( + NetworkServicesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NetworkServicesAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_network_services_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [NetworkServicesClient, NetworkServicesAsyncClient] +) +@mock.patch.object( + NetworkServicesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(NetworkServicesClient), +) +@mock.patch.object( + NetworkServicesAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(NetworkServicesAsyncClient), +) +def test_network_services_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [NetworkServicesClient, NetworkServicesAsyncClient] +) +@mock.patch.object( + NetworkServicesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NetworkServicesClient), +) +@mock.patch.object( + NetworkServicesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NetworkServicesAsyncClient), +) +def test_network_services_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = NetworkServicesClient._DEFAULT_UNIVERSE + default_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = NetworkServicesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport, "grpc"), + ( + NetworkServicesAsyncClient, + transports.NetworkServicesGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest"), + ], +) +def test_network_services_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + NetworkServicesClient, + transports.NetworkServicesGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + NetworkServicesAsyncClient, + transports.NetworkServicesGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (NetworkServicesClient, transports.NetworkServicesRestTransport, "rest", None), + ], +) +def test_network_services_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_network_services_client_client_options_from_dict(): + with mock.patch( + "google.cloud.network_services_v1beta1.services.network_services.transports.NetworkServicesGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = NetworkServicesClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + NetworkServicesClient, + transports.NetworkServicesGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + NetworkServicesAsyncClient, + transports.NetworkServicesGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_network_services_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networkservices.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.ListEndpointPoliciesRequest(), + {}, + ], +) +def test_list_endpoint_policies(request_type, transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.ListEndpointPoliciesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = endpoint_policy.ListEndpointPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_endpoint_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = endpoint_policy.ListEndpointPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_endpoint_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.ListEndpointPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_endpoint_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_endpoint_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_endpoint_policies] = ( + mock_rpc + ) + request = {} + client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_endpoint_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_endpoint_policies + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_endpoint_policies + ] = mock_rpc + + request = {} + await client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_endpoint_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.ListEndpointPoliciesRequest(), + {}, + ], +) +async def test_list_endpoint_policies_async( + request_type, transport: str = "grpc_asyncio" +): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.ListEndpointPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = endpoint_policy.ListEndpointPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_endpoint_policies_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.ListEndpointPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + call.return_value = endpoint_policy.ListEndpointPoliciesResponse() + client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.ListEndpointPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.ListEndpointPoliciesResponse() + ) + await client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_endpoint_policies_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.ListEndpointPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_endpoint_policies( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_endpoint_policies_flattened_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_endpoint_policies( + endpoint_policy.ListEndpointPoliciesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.ListEndpointPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.ListEndpointPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_endpoint_policies( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_endpoint_policies( + endpoint_policy.ListEndpointPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_endpoint_policies_pager(transport_name: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token="abc", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token="def", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token="ghi", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_endpoint_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, endpoint_policy.EndpointPolicy) for i in results) + + +def test_list_endpoint_policies_pages(transport_name: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token="abc", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token="def", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token="ghi", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_endpoint_policies(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_async_pager(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token="abc", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token="def", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token="ghi", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_endpoint_policies( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, endpoint_policy.EndpointPolicy) for i in responses) + + +@pytest.mark.asyncio +async def test_list_endpoint_policies_async_pages(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token="abc", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token="def", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token="ghi", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_endpoint_policies(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.GetEndpointPolicyRequest(), + {}, + ], +) +def test_get_endpoint_policy(request_type, transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.EndpointPolicy( + name="name_value", + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy="authorization_policy_value", + description="description_value", + server_tls_policy="server_tls_policy_value", + client_tls_policy="client_tls_policy_value", + ) + response = client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = endpoint_policy.GetEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint_policy.EndpointPolicy) + assert response.name == "name_value" + assert ( + response.type_ + == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY + ) + assert response.authorization_policy == "authorization_policy_value" + assert response.description == "description_value" + assert response.server_tls_policy == "server_tls_policy_value" + assert response.client_tls_policy == "client_tls_policy_value" + + +def test_get_endpoint_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = endpoint_policy.GetEndpointPolicyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.GetEndpointPolicyRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_endpoint_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_endpoint_policy in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_endpoint_policy] = ( + mock_rpc + ) + request = {} + client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_endpoint_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_endpoint_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_endpoint_policy + ] = mock_rpc + + request = {} + await client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.GetEndpointPolicyRequest(), + {}, + ], +) +async def test_get_endpoint_policy_async(request_type, transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.EndpointPolicy( + name="name_value", + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy="authorization_policy_value", + description="description_value", + server_tls_policy="server_tls_policy_value", + client_tls_policy="client_tls_policy_value", + ) + ) + response = await client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = endpoint_policy.GetEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint_policy.EndpointPolicy) + assert response.name == "name_value" + assert ( + response.type_ + == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY + ) + assert response.authorization_policy == "authorization_policy_value" + assert response.description == "description_value" + assert response.server_tls_policy == "server_tls_policy_value" + assert response.client_tls_policy == "client_tls_policy_value" + + +def test_get_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.GetEndpointPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + call.return_value = endpoint_policy.EndpointPolicy() + client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.GetEndpointPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.EndpointPolicy() + ) + await client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.EndpointPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_endpoint_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_endpoint_policy( + endpoint_policy.GetEndpointPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint_policy.EndpointPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.EndpointPolicy() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_endpoint_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_endpoint_policy( + endpoint_policy.GetEndpointPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + {}, + ], +) +def test_create_endpoint_policy(request_type, transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_endpoint_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_endpoint_policy.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.CreateEndpointPolicyRequest( + parent="parent_value", + endpoint_policy_id="endpoint_policy_id_value", + ) + assert args[0] == request_msg + + +def test_create_endpoint_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_endpoint_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_endpoint_policy] = ( + mock_rpc + ) + request = {} + client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_endpoint_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_endpoint_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_endpoint_policy + ] = mock_rpc + + request = {} + await client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + {}, + ], +) +async def test_create_endpoint_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_endpoint_policy( + parent="parent_value", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(name="name_value") + assert arg == mock_val + arg = args[0].endpoint_policy_id + mock_val = "endpoint_policy_id_value" + assert arg == mock_val + + +def test_create_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_endpoint_policy( + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + parent="parent_value", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_endpoint_policy( + parent="parent_value", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(name="name_value") + assert arg == mock_val + arg = args[0].endpoint_policy_id + mock_val = "endpoint_policy_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_endpoint_policy( + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + parent="parent_value", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + {}, + ], +) +def test_update_endpoint_policy(request_type, transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_endpoint_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + assert args[0] == request_msg + + +def test_update_endpoint_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_endpoint_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_endpoint_policy] = ( + mock_rpc + ) + request = {} + client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_endpoint_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_endpoint_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_endpoint_policy + ] = mock_rpc + + request = {} + await client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + {}, + ], +) +async def test_update_endpoint_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + + request.endpoint_policy.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "endpoint_policy.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + + request.endpoint_policy.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "endpoint_policy.name=name_value", + ) in kw["metadata"] + + +def test_update_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_endpoint_policy( + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_endpoint_policy( + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_endpoint_policy( + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].endpoint_policy + mock_val = gcn_endpoint_policy.EndpointPolicy(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_endpoint_policy( + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.DeleteEndpointPolicyRequest(), + {}, + ], +) +def test_delete_endpoint_policy(request_type, transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = endpoint_policy.DeleteEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_endpoint_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = endpoint_policy.DeleteEndpointPolicyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_endpoint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.DeleteEndpointPolicyRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_endpoint_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_endpoint_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_endpoint_policy] = ( + mock_rpc + ) + request = {} + client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_endpoint_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_endpoint_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_endpoint_policy + ] = mock_rpc + + request = {} + await client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.DeleteEndpointPolicyRequest(), + {}, + ], +) +async def test_delete_endpoint_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = endpoint_policy.DeleteEndpointPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_endpoint_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.DeleteEndpointPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_endpoint_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = endpoint_policy.DeleteEndpointPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_endpoint_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_endpoint_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_endpoint_policy_flattened_error(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_endpoint_policy( + endpoint_policy.DeleteEndpointPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_endpoint_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_endpoint_policy( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_endpoint_policy_flattened_error_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_endpoint_policy( + endpoint_policy.DeleteEndpointPolicyRequest(), + name="name_value", + ) + + +def test_list_endpoint_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_endpoint_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_endpoint_policies] = ( + mock_rpc + ) + + request = {} + client.list_endpoint_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_endpoint_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_endpoint_policies_rest_required_fields( + request_type=endpoint_policy.ListEndpointPoliciesRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListEndpointPolicies, + "_BaseListEndpointPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.ListEndpointPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_endpoint_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_endpoint_policies_rest_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.ListEndpointPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_endpoint_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/endpointPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_endpoint_policies_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_endpoint_policies( + endpoint_policy.ListEndpointPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_endpoint_policies_rest_pager(transport: str = "rest"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + next_page_token="abc", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[], + next_page_token="def", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + ], + next_page_token="ghi", + ), + endpoint_policy.ListEndpointPoliciesResponse( + endpoint_policies=[ + endpoint_policy.EndpointPolicy(), + endpoint_policy.EndpointPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + endpoint_policy.ListEndpointPoliciesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_endpoint_policies(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, endpoint_policy.EndpointPolicy) for i in results) + + pages = list(client.list_endpoint_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_endpoint_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_endpoint_policy in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_endpoint_policy] = ( + mock_rpc + ) + + request = {} + client.get_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_endpoint_policy_rest_required_fields( + request_type=endpoint_policy.GetEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetEndpointPolicy, + "_BaseGetEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.EndpointPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = endpoint_policy.EndpointPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_endpoint_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.EndpointPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = endpoint_policy.EndpointPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/endpointPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_endpoint_policy( + endpoint_policy.GetEndpointPolicyRequest(), + name="name_value", + ) + + +def test_create_endpoint_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_endpoint_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_endpoint_policy] = ( + mock_rpc + ) + + request = {} + client.create_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_endpoint_policy_rest_required_fields( + request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["endpoint_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "endpointPolicyId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateEndpointPolicy, + "_BaseCreateEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "endpointPolicyId" in jsonified_request + assert jsonified_request["endpointPolicyId"] == request_init["endpoint_policy_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["endpointPolicyId"] = "endpoint_policy_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("endpointPolicyId",)) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "endpointPolicyId" in jsonified_request + assert jsonified_request["endpointPolicyId"] == "endpoint_policy_id_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_endpoint_policy(request) + + expected_params = [ + ( + "endpointPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/endpointPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_endpoint_policy( + gcn_endpoint_policy.CreateEndpointPolicyRequest(), + parent="parent_value", + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + endpoint_policy_id="endpoint_policy_id_value", + ) + + +def test_update_endpoint_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_endpoint_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_endpoint_policy] = ( + mock_rpc + ) + + request = {} + client.update_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_endpoint_policy_rest_required_fields( + request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateEndpointPolicy, + "_BaseUpdateEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_endpoint_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "endpoint_policy": { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{endpoint_policy.name=projects/*/locations/*/endpointPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_endpoint_policy( + gcn_endpoint_policy.UpdateEndpointPolicyRequest(), + endpoint_policy=gcn_endpoint_policy.EndpointPolicy(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_endpoint_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_endpoint_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_endpoint_policy] = ( + mock_rpc + ) + + request = {} + client.delete_endpoint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_endpoint_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_endpoint_policy_rest_required_fields( + request_type=endpoint_policy.DeleteEndpointPolicyRequest, +): + transport_class = transports.NetworkServicesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteEndpointPolicy, + "_BaseDeleteEndpointPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_endpoint_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_endpoint_policy_rest_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_endpoint_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/endpointPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_endpoint_policy_rest_flattened_error(transport: str = "rest"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_endpoint_policy( + endpoint_policy.DeleteEndpointPolicyRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServicesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkServicesClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NetworkServicesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + transports.NetworkServicesRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = NetworkServicesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_endpoint_policies_empty_call_grpc(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + call.return_value = endpoint_policy.ListEndpointPoliciesResponse() + client.list_endpoint_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.ListEndpointPoliciesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_endpoint_policy_empty_call_grpc(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + call.return_value = endpoint_policy.EndpointPolicy() + client.get_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.GetEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_endpoint_policy_empty_call_grpc(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.CreateEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_endpoint_policy_empty_call_grpc(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_endpoint_policy_empty_call_grpc(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.DeleteEndpointPolicyRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = NetworkServicesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_endpoint_policies_empty_call_grpc_asyncio(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.ListEndpointPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_endpoint_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.ListEndpointPoliciesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_endpoint_policy_empty_call_grpc_asyncio(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint_policy.EndpointPolicy( + name="name_value", + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy="authorization_policy_value", + description="description_value", + server_tls_policy="server_tls_policy_value", + client_tls_policy="client_tls_policy_value", + ) + ) + await client.get_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.GetEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_endpoint_policy_empty_call_grpc_asyncio(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.CreateEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_endpoint_policy_empty_call_grpc_asyncio(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_endpoint_policy_empty_call_grpc_asyncio(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.DeleteEndpointPolicyRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = NetworkServicesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_endpoint_policies_rest_bad_request( + request_type=endpoint_policy.ListEndpointPoliciesRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_endpoint_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.ListEndpointPoliciesRequest, + dict, + ], +) +def test_list_endpoint_policies_rest_call_success(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.ListEndpointPoliciesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = endpoint_policy.ListEndpointPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_endpoint_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_endpoint_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.NetworkServicesRestInterceptor, "post_list_endpoint_policies" + ) as post, + mock.patch.object( + transports.NetworkServicesRestInterceptor, + "post_list_endpoint_policies_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_list_endpoint_policies" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = endpoint_policy.ListEndpointPoliciesRequest.pb( + endpoint_policy.ListEndpointPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = endpoint_policy.ListEndpointPoliciesResponse.to_json( + endpoint_policy.ListEndpointPoliciesResponse() + ) + req.return_value.content = return_value + + request = endpoint_policy.ListEndpointPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = endpoint_policy.ListEndpointPoliciesResponse() + post_with_metadata.return_value = ( + endpoint_policy.ListEndpointPoliciesResponse(), + metadata, + ) + + client.list_endpoint_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_endpoint_policy_rest_bad_request( + request_type=endpoint_policy.GetEndpointPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_endpoint_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.GetEndpointPolicyRequest, + dict, + ], +) +def test_get_endpoint_policy_rest_call_success(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = endpoint_policy.EndpointPolicy( + name="name_value", + type_=endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY, + authorization_policy="authorization_policy_value", + description="description_value", + server_tls_policy="server_tls_policy_value", + client_tls_policy="client_tls_policy_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = endpoint_policy.EndpointPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_endpoint_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint_policy.EndpointPolicy) + assert response.name == "name_value" + assert ( + response.type_ + == endpoint_policy.EndpointPolicy.EndpointPolicyType.SIDECAR_PROXY + ) + assert response.authorization_policy == "authorization_policy_value" + assert response.description == "description_value" + assert response.server_tls_policy == "server_tls_policy_value" + assert response.client_tls_policy == "client_tls_policy_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.NetworkServicesRestInterceptor, "post_get_endpoint_policy" + ) as post, + mock.patch.object( + transports.NetworkServicesRestInterceptor, + "post_get_endpoint_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_get_endpoint_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = endpoint_policy.GetEndpointPolicyRequest.pb( + endpoint_policy.GetEndpointPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = endpoint_policy.EndpointPolicy.to_json( + endpoint_policy.EndpointPolicy() + ) + req.return_value.content = return_value + + request = endpoint_policy.GetEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = endpoint_policy.EndpointPolicy() + post_with_metadata.return_value = endpoint_policy.EndpointPolicy(), metadata + + client.get_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_endpoint_policy_rest_bad_request( + request_type=gcn_endpoint_policy.CreateEndpointPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_endpoint_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.CreateEndpointPolicyRequest, + dict, + ], +) +def test_create_endpoint_policy_rest_call_success(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["endpoint_policy"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "authorization_policy": "authorization_policy_value", + "endpoint_matcher": { + "metadata_label_matcher": { + "metadata_label_match_criteria": 1, + "metadata_labels": [ + { + "label_name": "label_name_value", + "label_value": "label_value_value", + } + ], + } + }, + "traffic_port_selector": {"ports": ["ports_value1", "ports_value2"]}, + "description": "description_value", + "server_tls_policy": "server_tls_policy_value", + "client_tls_policy": "client_tls_policy_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_endpoint_policy.CreateEndpointPolicyRequest.meta.fields[ + "endpoint_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["endpoint_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["endpoint_policy"][field])): + del request_init["endpoint_policy"][field][i][subfield] + else: + del request_init["endpoint_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_endpoint_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.NetworkServicesRestInterceptor, "post_create_endpoint_policy" + ) as post, + mock.patch.object( + transports.NetworkServicesRestInterceptor, + "post_create_endpoint_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_create_endpoint_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_endpoint_policy.CreateEndpointPolicyRequest.pb( + gcn_endpoint_policy.CreateEndpointPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_endpoint_policy.CreateEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_endpoint_policy_rest_bad_request( + request_type=gcn_endpoint_policy.UpdateEndpointPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "endpoint_policy": { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_endpoint_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcn_endpoint_policy.UpdateEndpointPolicyRequest, + dict, + ], +) +def test_update_endpoint_policy_rest_call_success(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "endpoint_policy": { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + } + request_init["endpoint_policy"] = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "authorization_policy": "authorization_policy_value", + "endpoint_matcher": { + "metadata_label_matcher": { + "metadata_label_match_criteria": 1, + "metadata_labels": [ + { + "label_name": "label_name_value", + "label_value": "label_value_value", + } + ], + } + }, + "traffic_port_selector": {"ports": ["ports_value1", "ports_value2"]}, + "description": "description_value", + "server_tls_policy": "server_tls_policy_value", + "client_tls_policy": "client_tls_policy_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_endpoint_policy.UpdateEndpointPolicyRequest.meta.fields[ + "endpoint_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["endpoint_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["endpoint_policy"][field])): + del request_init["endpoint_policy"][field][i][subfield] + else: + del request_init["endpoint_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_endpoint_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.NetworkServicesRestInterceptor, "post_update_endpoint_policy" + ) as post, + mock.patch.object( + transports.NetworkServicesRestInterceptor, + "post_update_endpoint_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_update_endpoint_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_endpoint_policy.UpdateEndpointPolicyRequest.pb( + gcn_endpoint_policy.UpdateEndpointPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_endpoint_policy_rest_bad_request( + request_type=endpoint_policy.DeleteEndpointPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_endpoint_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + endpoint_policy.DeleteEndpointPolicyRequest, + dict, + ], +) +def test_delete_endpoint_policy_rest_call_success(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_endpoint_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_endpoint_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServicesRestInterceptor(), + ) + client = NetworkServicesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.NetworkServicesRestInterceptor, "post_delete_endpoint_policy" + ) as post, + mock.patch.object( + transports.NetworkServicesRestInterceptor, + "post_delete_endpoint_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServicesRestInterceptor, "pre_delete_endpoint_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = endpoint_policy.DeleteEndpointPolicyRequest.pb( + endpoint_policy.DeleteEndpointPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = endpoint_policy.DeleteEndpointPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_endpoint_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/endpointPolicies/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/endpointPolicies/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/endpointPolicies/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/endpointPolicies/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_endpoint_policies_empty_call_rest(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoint_policies), "__call__" + ) as call: + client.list_endpoint_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.ListEndpointPoliciesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_endpoint_policy_empty_call_rest(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_endpoint_policy), "__call__" + ) as call: + client.get_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.GetEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_endpoint_policy_empty_call_rest(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_endpoint_policy), "__call__" + ) as call: + client.create_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.CreateEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_endpoint_policy_empty_call_rest(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_endpoint_policy), "__call__" + ) as call: + client.update_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_endpoint_policy.UpdateEndpointPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_endpoint_policy_empty_call_rest(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_endpoint_policy), "__call__" + ) as call: + client.delete_endpoint_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = endpoint_policy.DeleteEndpointPolicyRequest() + assert args[0] == request_msg + + +def test_network_services_rest_lro_client(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.NetworkServicesGrpcTransport, + ) + + +def test_network_services_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NetworkServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_network_services_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.network_services_v1beta1.services.network_services.transports.NetworkServicesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.NetworkServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_endpoint_policies", + "get_endpoint_policy", + "create_endpoint_policy", + "update_endpoint_policy", + "delete_endpoint_policy", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_network_services_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.network_services_v1beta1.services.network_services.transports.NetworkServicesTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkServicesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_network_services_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.network_services_v1beta1.services.network_services.transports.NetworkServicesTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkServicesTransport() + adc.assert_called_once() + + +def test_network_services_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + NetworkServicesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + ], +) +def test_network_services_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + transports.NetworkServicesRestTransport, + ], +) +def test_network_services_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.NetworkServicesGrpcTransport, grpc_helpers), + (transports.NetworkServicesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_network_services_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "networkservices.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="networkservices.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + ], +) +def test_network_services_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_network_services_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.NetworkServicesRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_network_services_host_no_port(transport_name): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networkservices.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networkservices.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_network_services_host_with_port(transport_name): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networkservices.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networkservices.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkservices.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_network_services_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NetworkServicesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NetworkServicesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_endpoint_policies._session + session2 = client2.transport.list_endpoint_policies._session + assert session1 != session2 + session1 = client1.transport.get_endpoint_policy._session + session2 = client2.transport.get_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.create_endpoint_policy._session + session2 = client2.transport.create_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.update_endpoint_policy._session + session2 = client2.transport.update_endpoint_policy._session + assert session1 != session2 + session1 = client1.transport.delete_endpoint_policy._session + session2 = client2.transport.delete_endpoint_policy._session + assert session1 != session2 + + +def test_network_services_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkServicesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_network_services_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkServicesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + ], +) +def test_network_services_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServicesGrpcTransport, + transports.NetworkServicesGrpcAsyncIOTransport, + ], +) +def test_network_services_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_network_services_grpc_lro_client(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_network_services_grpc_lro_async_client(): + client = NetworkServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_authorization_policy_path(): + project = "squid" + location = "clam" + authorization_policy = "whelk" + expected = "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format( + project=project, + location=location, + authorization_policy=authorization_policy, + ) + actual = NetworkServicesClient.authorization_policy_path( + project, location, authorization_policy + ) + assert expected == actual + + +def test_parse_authorization_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "authorization_policy": "nudibranch", + } + path = NetworkServicesClient.authorization_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_authorization_policy_path(path) + assert expected == actual + + +def test_client_tls_policy_path(): + project = "cuttlefish" + location = "mussel" + client_tls_policy = "winkle" + expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format( + project=project, + location=location, + client_tls_policy=client_tls_policy, + ) + actual = NetworkServicesClient.client_tls_policy_path( + project, location, client_tls_policy + ) + assert expected == actual + + +def test_parse_client_tls_policy_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "client_tls_policy": "abalone", + } + path = NetworkServicesClient.client_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_client_tls_policy_path(path) + assert expected == actual + + +def test_endpoint_policy_path(): + project = "squid" + location = "clam" + endpoint_policy = "whelk" + expected = "projects/{project}/locations/{location}/endpointPolicies/{endpoint_policy}".format( + project=project, + location=location, + endpoint_policy=endpoint_policy, + ) + actual = NetworkServicesClient.endpoint_policy_path( + project, location, endpoint_policy + ) + assert expected == actual + + +def test_parse_endpoint_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "endpoint_policy": "nudibranch", + } + path = NetworkServicesClient.endpoint_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_endpoint_policy_path(path) + assert expected == actual + + +def test_server_tls_policy_path(): + project = "cuttlefish" + location = "mussel" + server_tls_policy = "winkle" + expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format( + project=project, + location=location, + server_tls_policy=server_tls_policy, + ) + actual = NetworkServicesClient.server_tls_policy_path( + project, location, server_tls_policy + ) + assert expected == actual + + +def test_parse_server_tls_policy_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "server_tls_policy": "abalone", + } + path = NetworkServicesClient.server_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_server_tls_policy_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = NetworkServicesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = NetworkServicesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = NetworkServicesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = NetworkServicesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = NetworkServicesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = NetworkServicesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = NetworkServicesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = NetworkServicesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = NetworkServicesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = NetworkServicesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServicesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.NetworkServicesTransport, "_prep_wrapped_messages" + ) as prep: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.NetworkServicesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = NetworkServicesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = NetworkServicesClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = NetworkServicesAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = NetworkServicesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = NetworkServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (NetworkServicesClient, transports.NetworkServicesGrpcTransport), + (NetworkServicesAsyncClient, transports.NetworkServicesGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-pubsub/CHANGELOG.md b/packages/google-cloud-pubsub/CHANGELOG.md index 24afa6230e49..69dea7b67572 100644 --- a/packages/google-cloud-pubsub/CHANGELOG.md +++ b/packages/google-cloud-pubsub/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-pubsub/#history +## [2.41.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-pubsub-v2.40.0...google-cloud-pubsub-v2.41.0) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [2.40.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-pubsub-v2.39.2...google-cloud-pubsub-v2.40.0) (2026-09-03) diff --git a/packages/google-cloud-pubsub/google/pubsub/__init__.py b/packages/google-cloud-pubsub/google/pubsub/__init__.py index e416a621c132..91d72c5515b4 100644 --- a/packages/google-cloud-pubsub/google/pubsub/__init__.py +++ b/packages/google-cloud-pubsub/google/pubsub/__init__.py @@ -64,6 +64,7 @@ PlatformLogsSettings, PublishRequest, PublishResponse, + PubsubClientTelemetry, PubsubMessage, PullRequest, PullResponse, @@ -147,6 +148,7 @@ "PlatformLogsSettings", "PublishRequest", "PublishResponse", + "PubsubClientTelemetry", "PubsubMessage", "PullRequest", "PullResponse", diff --git a/packages/google-cloud-pubsub/google/pubsub/gapic_version.py b/packages/google-cloud-pubsub/google/pubsub/gapic_version.py index f7d52da46b26..c61e57da3614 100644 --- a/packages/google-cloud-pubsub/google/pubsub/gapic_version.py +++ b/packages/google-cloud-pubsub/google/pubsub/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.40.0" # {x-release-please-version} +__version__ = "2.41.0" # {x-release-please-version} diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py b/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py index 79ef1311ebb5..33033e1c9fea 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py @@ -75,6 +75,7 @@ PlatformLogsSettings, PublishRequest, PublishResponse, + PubsubClientTelemetry, PubsubMessage, PullRequest, PullResponse, @@ -167,6 +168,7 @@ "PublishRequest", "PublishResponse", "PublisherClient", + "PubsubClientTelemetry", "PubsubMessage", "PullRequest", "PullResponse", diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/gapic_version.py b/packages/google-cloud-pubsub/google/pubsub_v1/gapic_version.py index f7d52da46b26..c61e57da3614 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/gapic_version.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.40.0" # {x-release-please-version} +__version__ = "2.41.0" # {x-release-please-version} diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py b/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py index 565aaa43ce52..07c671c1b85b 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py @@ -53,6 +53,7 @@ PlatformLogsSettings, PublishRequest, PublishResponse, + PubsubClientTelemetry, PubsubMessage, PullRequest, PullResponse, @@ -139,6 +140,7 @@ "PlatformLogsSettings", "PublishRequest", "PublishResponse", + "PubsubClientTelemetry", "PubsubMessage", "PullRequest", "PullResponse", diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py b/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py index 77572a373949..fe7a12277d1e 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py @@ -82,6 +82,7 @@ "DeleteSnapshotRequest", "SeekRequest", "SeekResponse", + "PubsubClientTelemetry", }, ) @@ -3931,4 +3932,57 @@ class SeekResponse(proto.Message): r"""Response for the ``Seek`` method (this response is empty).""" +class PubsubClientTelemetry(proto.Message): + r"""Client-side telemetry about Pub/Sub requests, useful for debugging + purposes. If the client opts to provide this information, it will be + passed as a serialized proto in the + ``x-goog-pubsub-client-telemetry`` header. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + publish_operation (google.pubsub_v1.types.PubsubClientTelemetry.PublishOperation): + Optional. Telemetry about a ``Publish`` operation. + + This field is a member of `oneof`_ ``operation``. + """ + + class PublishOperation(proto.Message): + r"""Telemetry about a ``Publish`` operation which may or may not be + common across individual RPCs. + + Attributes: + hedged_attempt_count (int): + Optional. If the publisher client is using + publish hedging, provides the attempt count for + the hedge (starting at 1). A value of 0 + indicates that the request was not hedged. + publish_start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Time at which the ``publish()`` call was initiated + in the client library, meaning across all RPC retry + attempts, see `grpc + retries `__. Provides a + sense of the end-to-end publish duration from the client + perspective, across retries. + """ + + hedged_attempt_count: int = proto.Field( + proto.INT32, + number=1, + ) + publish_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + publish_operation: PublishOperation = proto.Field( + proto.MESSAGE, + number=1, + oneof="operation", + message=PublishOperation, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json b/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json index ba17b2637d0d..bef8111fb59c 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json +++ b/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-pubsub", - "version": "2.40.0" + "version": "2.41.0" }, "snippets": [ { diff --git a/packages/google-cloud-securesourcemanager/CHANGELOG.md b/packages/google-cloud-securesourcemanager/CHANGELOG.md index 35f5b5a56da6..699fac2c45da 100644 --- a/packages/google-cloud-securesourcemanager/CHANGELOG.md +++ b/packages/google-cloud-securesourcemanager/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-securesourcemanager/#history +## [0.6.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securesourcemanager-v0.6.1...google-cloud-securesourcemanager-v0.6.2) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.6.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securesourcemanager-v0.6.0...google-cloud-securesourcemanager-v0.6.1) (2026-07-07) diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/__init__.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/__init__.py index 96b86d6afd16..f2d1750c6316 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/__init__.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/__init__.py @@ -47,6 +47,8 @@ DeleteRepositoryRequest, FetchBlobRequest, FetchBlobResponse, + FetchRefsRequest, + FetchRefsResponse, FetchTreeRequest, FetchTreeResponse, FileDiff, @@ -86,6 +88,7 @@ OperationMetadata, PullRequest, PullRequestComment, + Ref, Repository, ResolvePullRequestCommentsRequest, ResolvePullRequestCommentsResponse, @@ -126,6 +129,8 @@ "DeleteRepositoryRequest", "FetchBlobRequest", "FetchBlobResponse", + "FetchRefsRequest", + "FetchRefsResponse", "FetchTreeRequest", "FetchTreeResponse", "FileDiff", @@ -165,6 +170,7 @@ "OperationMetadata", "PullRequest", "PullRequestComment", + "Ref", "Repository", "ResolvePullRequestCommentsRequest", "ResolvePullRequestCommentsResponse", diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py index 4c89af3224e4..5e6be3be54dd 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.1" # {x-release-please-version} +__version__ = "0.6.2" # {x-release-please-version} diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/__init__.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/__init__.py index 3993a14623fa..feef43620617 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/__init__.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/__init__.py @@ -58,6 +58,8 @@ DeleteRepositoryRequest, FetchBlobRequest, FetchBlobResponse, + FetchRefsRequest, + FetchRefsResponse, FetchTreeRequest, FetchTreeResponse, FileDiff, @@ -97,6 +99,7 @@ OperationMetadata, PullRequest, PullRequestComment, + Ref, Repository, ResolvePullRequestCommentsRequest, ResolvePullRequestCommentsResponse, @@ -136,6 +139,8 @@ "DeleteRepositoryRequest", "FetchBlobRequest", "FetchBlobResponse", + "FetchRefsRequest", + "FetchRefsResponse", "FetchTreeRequest", "FetchTreeResponse", "FileDiff", @@ -175,6 +180,7 @@ "OperationMetadata", "PullRequest", "PullRequestComment", + "Ref", "Repository", "ResolvePullRequestCommentsRequest", "ResolvePullRequestCommentsResponse", diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_metadata.json b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_metadata.json index f037a162e26e..1d76895467cc 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_metadata.json +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_metadata.json @@ -105,6 +105,11 @@ "fetch_blob" ] }, + "FetchRefs": { + "methods": [ + "fetch_refs" + ] + }, "FetchTree": { "methods": [ "fetch_tree" @@ -370,6 +375,11 @@ "fetch_blob" ] }, + "FetchRefs": { + "methods": [ + "fetch_refs" + ] + }, "FetchTree": { "methods": [ "fetch_tree" @@ -635,6 +645,11 @@ "fetch_blob" ] }, + "FetchRefs": { + "methods": [ + "fetch_refs" + ] + }, "FetchTree": { "methods": [ "fetch_tree" diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_version.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_version.py index 4c89af3224e4..5e6be3be54dd 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_version.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.1" # {x-release-please-version} +__version__ = "0.6.2" # {x-release-please-version} diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py index 0b16c0bd0e25..da0f7b59317f 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py @@ -4513,6 +4513,109 @@ async def sample_fetch_blob(): # Done; return the response. return response + async def fetch_refs( + self, + request: Optional[Union[secure_source_manager.FetchRefsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchRefsAsyncPager: + r"""Fetches git references from a repository. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securesourcemanager_v1 + + async def sample_fetch_refs(): + # Create a client + client = securesourcemanager_v1.SecureSourceManagerAsyncClient() + + # Initialize request argument(s) + request = securesourcemanager_v1.FetchRefsRequest( + repository="repository_value", + ) + + # Make the request + page_result = client.fetch_refs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securesourcemanager_v1.types.FetchRefsRequest, dict]]): + The request object. Request message for fetching git + references from a repository. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.securesourcemanager_v1.services.secure_source_manager.pagers.FetchRefsAsyncPager: + Response message containing a list of + git references. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, secure_source_manager.FetchRefsRequest): + request = secure_source_manager.FetchRefsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_refs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("repository", request.repository),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchRefsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def create_issue( self, request: Optional[Union[secure_source_manager.CreateIssueRequest, dict]] = None, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py index 2608fd44309d..d0cda77eb81e 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py @@ -4967,6 +4967,107 @@ def sample_fetch_blob(): # Done; return the response. return response + def fetch_refs( + self, + request: Optional[Union[secure_source_manager.FetchRefsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchRefsPager: + r"""Fetches git references from a repository. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securesourcemanager_v1 + + def sample_fetch_refs(): + # Create a client + client = securesourcemanager_v1.SecureSourceManagerClient() + + # Initialize request argument(s) + request = securesourcemanager_v1.FetchRefsRequest( + repository="repository_value", + ) + + # Make the request + page_result = client.fetch_refs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securesourcemanager_v1.types.FetchRefsRequest, dict]): + The request object. Request message for fetching git + references from a repository. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.securesourcemanager_v1.services.secure_source_manager.pagers.FetchRefsPager: + Response message containing a list of + git references. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, secure_source_manager.FetchRefsRequest): + request = secure_source_manager.FetchRefsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_refs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("repository", request.repository),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchRefsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def create_issue( self, request: Optional[Union[secure_source_manager.CreateIssueRequest, dict]] = None, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/pagers.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/pagers.py index b96e165f56c7..948af52fa1fa 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/pagers.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/pagers.py @@ -1147,6 +1147,162 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class FetchRefsPager: + """A pager for iterating through ``fetch_refs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securesourcemanager_v1.types.FetchRefsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``refs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchRefs`` requests and continue to iterate + through the ``refs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securesourcemanager_v1.types.FetchRefsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., secure_source_manager.FetchRefsResponse], + request: secure_source_manager.FetchRefsRequest, + response: secure_source_manager.FetchRefsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.securesourcemanager_v1.types.FetchRefsRequest): + The initial request object. + response (google.cloud.securesourcemanager_v1.types.FetchRefsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = secure_source_manager.FetchRefsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[secure_source_manager.FetchRefsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[secure_source_manager.Ref]: + for page in self.pages: + yield from page.refs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchRefsAsyncPager: + """A pager for iterating through ``fetch_refs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securesourcemanager_v1.types.FetchRefsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``refs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchRefs`` requests and continue to iterate + through the ``refs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securesourcemanager_v1.types.FetchRefsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[secure_source_manager.FetchRefsResponse]], + request: secure_source_manager.FetchRefsRequest, + response: secure_source_manager.FetchRefsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.securesourcemanager_v1.types.FetchRefsRequest): + The initial request object. + response (google.cloud.securesourcemanager_v1.types.FetchRefsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = secure_source_manager.FetchRefsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[secure_source_manager.FetchRefsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[secure_source_manager.Ref]: + async def async_generator(): + async for page in self.pages: + for response in page.refs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListIssuesPager: """A pager for iterating through ``list_issues`` requests. diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/base.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/base.py index c000bcc99cda..d799b3ee4f88 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/base.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/base.py @@ -45,7 +45,10 @@ class SecureSourceManagerTransport(abc.ABC): """Abstract transport class for SecureSourceManager.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/securesourcemanager.read-write", + ) DEFAULT_HOST: str = "securesourcemanager.googleapis.com" @@ -353,6 +356,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.fetch_refs: gapic_v1.method.wrap_method( + self.fetch_refs, + default_timeout=None, + client_info=client_info, + ), self.create_issue: gapic_v1.method.wrap_method( self.create_issue, default_timeout=None, @@ -840,6 +848,18 @@ def fetch_blob( ]: raise NotImplementedError() + @property + def fetch_refs( + self, + ) -> Callable[ + [secure_source_manager.FetchRefsRequest], + Union[ + secure_source_manager.FetchRefsResponse, + Awaitable[secure_source_manager.FetchRefsResponse], + ], + ]: + raise NotImplementedError() + @property def create_issue( self, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc.py index 086a1ff6f7e0..449d40645e7a 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc.py @@ -1260,6 +1260,35 @@ def fetch_blob( ) return self._stubs["fetch_blob"] + @property + def fetch_refs( + self, + ) -> Callable[ + [secure_source_manager.FetchRefsRequest], + secure_source_manager.FetchRefsResponse, + ]: + r"""Return a callable for the fetch refs method over gRPC. + + Fetches git references from a repository. + + Returns: + Callable[[~.FetchRefsRequest], + ~.FetchRefsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_refs" not in self._stubs: + self._stubs["fetch_refs"] = self._logged_channel.unary_unary( + "/google.cloud.securesourcemanager.v1.SecureSourceManager/FetchRefs", + request_serializer=secure_source_manager.FetchRefsRequest.serialize, + response_deserializer=secure_source_manager.FetchRefsResponse.deserialize, + ) + return self._stubs["fetch_refs"] + @property def create_issue( self, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc_asyncio.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc_asyncio.py index 5081f27254c9..8fc3fa2b09dc 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc_asyncio.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/grpc_asyncio.py @@ -1293,6 +1293,35 @@ def fetch_blob( ) return self._stubs["fetch_blob"] + @property + def fetch_refs( + self, + ) -> Callable[ + [secure_source_manager.FetchRefsRequest], + Awaitable[secure_source_manager.FetchRefsResponse], + ]: + r"""Return a callable for the fetch refs method over gRPC. + + Fetches git references from a repository. + + Returns: + Callable[[~.FetchRefsRequest], + Awaitable[~.FetchRefsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_refs" not in self._stubs: + self._stubs["fetch_refs"] = self._logged_channel.unary_unary( + "/google.cloud.securesourcemanager.v1.SecureSourceManager/FetchRefs", + request_serializer=secure_source_manager.FetchRefsRequest.serialize, + response_deserializer=secure_source_manager.FetchRefsResponse.deserialize, + ) + return self._stubs["fetch_refs"] + @property def create_issue( self, @@ -2107,6 +2136,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.fetch_refs: self._wrap_method( + self.fetch_refs, + default_timeout=None, + client_info=client_info, + ), self.create_issue: self._wrap_method( self.create_issue, default_timeout=None, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest.py index ae83f43e4b34..f474073321fd 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest.py @@ -232,6 +232,14 @@ def post_fetch_blob(self, response): logging.log(f"Received response: {response}") return response + def pre_fetch_refs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_refs(self, response): + logging.log(f"Received response: {response}") + return response + def pre_fetch_tree(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1431,6 +1439,56 @@ def post_fetch_blob_with_metadata( """ return response, metadata + def pre_fetch_refs( + self, + request: secure_source_manager.FetchRefsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + secure_source_manager.FetchRefsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for fetch_refs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecureSourceManager server. + """ + return request, metadata + + def post_fetch_refs( + self, response: secure_source_manager.FetchRefsResponse + ) -> secure_source_manager.FetchRefsResponse: + """Post-rpc interceptor for fetch_refs + + DEPRECATED. Please use the `post_fetch_refs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecureSourceManager server but before + it is returned to user code. This `post_fetch_refs` interceptor runs + before the `post_fetch_refs_with_metadata` interceptor. + """ + return response + + def post_fetch_refs_with_metadata( + self, + response: secure_source_manager.FetchRefsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + secure_source_manager.FetchRefsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for fetch_refs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecureSourceManager server but before it is returned to user code. + + We recommend only using this `post_fetch_refs_with_metadata` + interceptor in new development instead of the `post_fetch_refs` interceptor. + When both interceptors are used, this `post_fetch_refs_with_metadata` interceptor runs after the + `post_fetch_refs` interceptor. The (possibly modified) response returned by + `post_fetch_refs` will be passed to + `post_fetch_refs_with_metadata`. + """ + return response, metadata + def pre_fetch_tree( self, request: secure_source_manager.FetchTreeRequest, @@ -6286,6 +6344,157 @@ def __call__( ) return resp + class _FetchRefs( + _BaseSecureSourceManagerRestTransport._BaseFetchRefs, + SecureSourceManagerRestStub, + ): + def __hash__(self): + return hash("SecureSourceManagerRestTransport.FetchRefs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: secure_source_manager.FetchRefsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> secure_source_manager.FetchRefsResponse: + r"""Call the fetch refs method over HTTP. + + Args: + request (~.secure_source_manager.FetchRefsRequest): + The request object. Request message for fetching git + references from a repository. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.secure_source_manager.FetchRefsResponse: + Response message containing a list of + git references. + + """ + + http_options = ( + _BaseSecureSourceManagerRestTransport._BaseFetchRefs._get_http_options() + ) + request, metadata = self._interceptor.pre_fetch_refs(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseSecureSourceManagerRestTransport._BaseFetchRefs, + "_BaseFetchRefs__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.securesourcemanager_v1.SecureSourceManagerClient.FetchRefs", + extra={ + "serviceName": "google.cloud.securesourcemanager.v1.SecureSourceManager", + "rpcName": "FetchRefs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecureSourceManagerRestTransport._FetchRefs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = secure_source_manager.FetchRefsResponse() + pb_resp = secure_source_manager.FetchRefsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_refs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_fetch_refs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = secure_source_manager.FetchRefsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.securesourcemanager_v1.SecureSourceManagerClient.fetch_refs", + extra={ + "serviceName": "google.cloud.securesourcemanager.v1.SecureSourceManager", + "rpcName": "FetchRefs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _FetchTree( _BaseSecureSourceManagerRestTransport._BaseFetchTree, SecureSourceManagerRestStub, @@ -11581,6 +11790,17 @@ def fetch_blob( # In C++ this would require a dynamic_cast return self._FetchBlob(self._session, self._host, self._interceptor) # type: ignore + @property + def fetch_refs( + self, + ) -> Callable[ + [secure_source_manager.FetchRefsRequest], + secure_source_manager.FetchRefsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchRefs(self._session, self._host, self._interceptor) # type: ignore + @property def fetch_tree( self, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest_base.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest_base.py index 40f336915a5d..95fff593fffc 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest_base.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/transports/rest_base.py @@ -420,6 +420,22 @@ def _get_http_options(): ] return http_options + class _BaseFetchRefs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{repository=projects/*/locations/*/repositories/*}:fetchRefs", + }, + ] + return http_options + class _BaseFetchTree: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/__init__.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/__init__.py index ccba7b0d5e4b..0007803659f8 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/__init__.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/__init__.py @@ -36,6 +36,8 @@ DeleteRepositoryRequest, FetchBlobRequest, FetchBlobResponse, + FetchRefsRequest, + FetchRefsResponse, FetchTreeRequest, FetchTreeResponse, FileDiff, @@ -75,6 +77,7 @@ OperationMetadata, PullRequest, PullRequestComment, + Ref, Repository, ResolvePullRequestCommentsRequest, ResolvePullRequestCommentsResponse, @@ -113,6 +116,8 @@ "DeleteRepositoryRequest", "FetchBlobRequest", "FetchBlobResponse", + "FetchRefsRequest", + "FetchRefsResponse", "FetchTreeRequest", "FetchTreeResponse", "FileDiff", @@ -152,6 +157,7 @@ "OperationMetadata", "PullRequest", "PullRequestComment", + "Ref", "Repository", "ResolvePullRequestCommentsRequest", "ResolvePullRequestCommentsResponse", diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py index a12ad8333565..29e36b2408f8 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py @@ -33,6 +33,7 @@ "Issue", "IssueComment", "PullRequestComment", + "Ref", "ListInstancesRequest", "ListInstancesResponse", "GetInstanceRequest", @@ -80,6 +81,8 @@ "FetchTreeResponse", "FetchBlobRequest", "FetchBlobResponse", + "FetchRefsRequest", + "FetchRefsResponse", "ListPullRequestCommentsRequest", "ListPullRequestCommentsResponse", "CreatePullRequestCommentRequest", @@ -150,6 +153,10 @@ class Instance(proto.Message): Identity Federation to support third party identity provider. If unset, defaults to the Google OIDC IdP. + satisfies_pzi (bool): + Output only. Reserved for future use. + satisfies_pzs (bool): + Output only. Reserved for future use. """ class State(proto.Enum): @@ -386,6 +393,14 @@ class WorkforceIdentityFederationConfig(proto.Message): message=WorkforceIdentityFederationConfig, ) ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=18, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=19, + ) class Repository(proto.Message): @@ -817,11 +832,15 @@ class HookEventType(proto.Enum): PULL_REQUEST (2): Pull request events are triggered when a pull request is opened, closed, reopened, or edited. + PULL_REQUEST_COMMENT (3): + Triggers when a general comment is added, + edited, or deleted on a pull request. """ UNSPECIFIED = 0 PUSH = 1 PULL_REQUEST = 2 + PULL_REQUEST_COMMENT = 3 class PushOption(proto.Message): r""" @@ -1512,6 +1531,52 @@ class Position(proto.Message): ) +class Ref(proto.Message): + r"""Ref represents a git reference within a repository. + + Attributes: + name (str): + Identifier. Name of the git reference (e.g., + 'refs/heads/foo' or 'refs/tags/v1.0'). + target (str): + Output only. The target of the reference, + which is a commit SHA. + type_ (google.cloud.securesourcemanager_v1.types.Ref.RefType): + Output only. The type of the reference. + """ + + class RefType(proto.Enum): + r"""The derived type of the reference (e.g., branch or tag) from + the name. + + Values: + REF_TYPE_UNSPECIFIED (0): + Unspecified ref type. + REF_TYPE_BRANCH (1): + Represents a branch. + REF_TYPE_TAG (2): + Represents a tag. + """ + + REF_TYPE_UNSPECIFIED = 0 + REF_TYPE_BRANCH = 1 + REF_TYPE_TAG = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + target: str = proto.Field( + proto.STRING, + number=2, + ) + type_: RefType = proto.Field( + proto.ENUM, + number=3, + enum=RefType, + ) + + class ListInstancesRequest(proto.Message): r"""ListInstancesRequest is the request to list instances. @@ -2872,6 +2937,74 @@ class FetchBlobResponse(proto.Message): ) +class FetchRefsRequest(proto.Message): + r"""Request message for fetching git references from a + repository. + + Attributes: + repository (str): + Required. The format is + ``projects/{project_number}/locations/{location_id}/repositories/{repository_id}``. + Specifies the repository to fetch the references from. + type_ (google.cloud.securesourcemanager_v1.types.Ref.RefType): + Optional. The type of reference to fetch (eg. + branch, tag). By default, all references are + returned. + page_size (int): + Optional. Requested page size. If + unspecified, a default size of 30 will be used. + The maximum value is 100; values above 100 will + be coerced to 100. + page_token (str): + Optional. A token identifying a page of + results the server should return. + """ + + repository: str = proto.Field( + proto.STRING, + number=1, + ) + type_: "Ref.RefType" = proto.Field( + proto.ENUM, + number=2, + enum="Ref.RefType", + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class FetchRefsResponse(proto.Message): + r"""Response message containing a list of git references. + + Attributes: + refs (MutableSequence[google.cloud.securesourcemanager_v1.types.Ref]): + The list of git references. + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + refs: MutableSequence["Ref"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Ref", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + class ListPullRequestCommentsRequest(proto.Message): r"""The request to list pull request comments. diff --git a/packages/google-cloud-securesourcemanager/samples/generated_samples/securesourcemanager_v1_generated_secure_source_manager_fetch_refs_async.py b/packages/google-cloud-securesourcemanager/samples/generated_samples/securesourcemanager_v1_generated_secure_source_manager_fetch_refs_async.py new file mode 100644 index 000000000000..0e51f71acaae --- /dev/null +++ b/packages/google-cloud-securesourcemanager/samples/generated_samples/securesourcemanager_v1_generated_secure_source_manager_fetch_refs_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchRefs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securesourcemanager + + +# [START securesourcemanager_v1_generated_SecureSourceManager_FetchRefs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securesourcemanager_v1 + + +async def sample_fetch_refs(): + # Create a client + client = securesourcemanager_v1.SecureSourceManagerAsyncClient() + + # Initialize request argument(s) + request = securesourcemanager_v1.FetchRefsRequest( + repository="repository_value", + ) + + # Make the request + page_result = client.fetch_refs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END securesourcemanager_v1_generated_SecureSourceManager_FetchRefs_async] diff --git a/packages/google-cloud-securesourcemanager/samples/generated_samples/securesourcemanager_v1_generated_secure_source_manager_fetch_refs_sync.py b/packages/google-cloud-securesourcemanager/samples/generated_samples/securesourcemanager_v1_generated_secure_source_manager_fetch_refs_sync.py new file mode 100644 index 000000000000..9e36bee58fdd --- /dev/null +++ b/packages/google-cloud-securesourcemanager/samples/generated_samples/securesourcemanager_v1_generated_secure_source_manager_fetch_refs_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchRefs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securesourcemanager + + +# [START securesourcemanager_v1_generated_SecureSourceManager_FetchRefs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securesourcemanager_v1 + + +def sample_fetch_refs(): + # Create a client + client = securesourcemanager_v1.SecureSourceManagerClient() + + # Initialize request argument(s) + request = securesourcemanager_v1.FetchRefsRequest( + repository="repository_value", + ) + + # Make the request + page_result = client.fetch_refs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END securesourcemanager_v1_generated_SecureSourceManager_FetchRefs_sync] diff --git a/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json b/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json index e3d4d3b18f6a..772bb31d8709 100644 --- a/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json +++ b/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securesourcemanager", - "version": "0.6.1" + "version": "0.6.2" }, "snippets": [ { @@ -3166,6 +3166,159 @@ ], "title": "securesourcemanager_v1_generated_secure_source_manager_fetch_blob_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securesourcemanager_v1.SecureSourceManagerAsyncClient", + "shortName": "SecureSourceManagerAsyncClient" + }, + "fullName": "google.cloud.securesourcemanager_v1.SecureSourceManagerAsyncClient.fetch_refs", + "method": { + "fullName": "google.cloud.securesourcemanager.v1.SecureSourceManager.FetchRefs", + "service": { + "fullName": "google.cloud.securesourcemanager.v1.SecureSourceManager", + "shortName": "SecureSourceManager" + }, + "shortName": "FetchRefs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securesourcemanager_v1.types.FetchRefsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.securesourcemanager_v1.services.secure_source_manager.pagers.FetchRefsAsyncPager", + "shortName": "fetch_refs" + }, + "description": "Sample for FetchRefs", + "file": "securesourcemanager_v1_generated_secure_source_manager_fetch_refs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securesourcemanager_v1_generated_SecureSourceManager_FetchRefs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securesourcemanager_v1_generated_secure_source_manager_fetch_refs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securesourcemanager_v1.SecureSourceManagerClient", + "shortName": "SecureSourceManagerClient" + }, + "fullName": "google.cloud.securesourcemanager_v1.SecureSourceManagerClient.fetch_refs", + "method": { + "fullName": "google.cloud.securesourcemanager.v1.SecureSourceManager.FetchRefs", + "service": { + "fullName": "google.cloud.securesourcemanager.v1.SecureSourceManager", + "shortName": "SecureSourceManager" + }, + "shortName": "FetchRefs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securesourcemanager_v1.types.FetchRefsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.securesourcemanager_v1.services.secure_source_manager.pagers.FetchRefsPager", + "shortName": "fetch_refs" + }, + "description": "Sample for FetchRefs", + "file": "securesourcemanager_v1_generated_secure_source_manager_fetch_refs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securesourcemanager_v1_generated_SecureSourceManager_FetchRefs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securesourcemanager_v1_generated_secure_source_manager_fetch_refs_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py b/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py index d4740f876042..4a17cf1a0bc5 100644 --- a/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py +++ b/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py @@ -1112,7 +1112,10 @@ def test_secure_source_manager_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/securesourcemanager.read-write", + ), scopes=None, default_host="securesourcemanager.googleapis.com", ssl_credentials=None, @@ -1677,6 +1680,8 @@ def test_get_instance(request_type, transport: str = "grpc"): state=secure_source_manager.Instance.State.CREATING, state_note=secure_source_manager.Instance.StateNote.PAUSED_CMEK_UNAVAILABLE, kms_key="kms_key_value", + satisfies_pzi=True, + satisfies_pzs=True, ) response = client.get_instance(request) @@ -1695,6 +1700,8 @@ def test_get_instance(request_type, transport: str = "grpc"): == secure_source_manager.Instance.StateNote.PAUSED_CMEK_UNAVAILABLE ) assert response.kms_key == "kms_key_value" + assert response.satisfies_pzi is True + assert response.satisfies_pzs is True def test_get_instance_non_empty_request_with_auto_populated_field(): @@ -1830,6 +1837,8 @@ async def test_get_instance_async(request_type, transport: str = "grpc_asyncio") state=secure_source_manager.Instance.State.CREATING, state_note=secure_source_manager.Instance.StateNote.PAUSED_CMEK_UNAVAILABLE, kms_key="kms_key_value", + satisfies_pzi=True, + satisfies_pzs=True, ) ) response = await client.get_instance(request) @@ -1849,6 +1858,8 @@ async def test_get_instance_async(request_type, transport: str = "grpc_asyncio") == secure_source_manager.Instance.StateNote.PAUSED_CMEK_UNAVAILABLE ) assert response.kms_key == "kms_key_value" + assert response.satisfies_pzi is True + assert response.satisfies_pzs is True def test_get_instance_field_headers(): @@ -13432,6 +13443,443 @@ async def test_fetch_blob_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + secure_source_manager.FetchRefsRequest(), + {}, + ], +) +def test_fetch_refs(request_type, transport: str = "grpc"): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = secure_source_manager.FetchRefsResponse( + next_page_token="next_page_token_value", + ) + response = client.fetch_refs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = secure_source_manager.FetchRefsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchRefsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_refs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = secure_source_manager.FetchRefsRequest( + repository="repository_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_refs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = secure_source_manager.FetchRefsRequest( + repository="repository_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_fetch_refs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.fetch_refs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.fetch_refs] = mock_rpc + request = {} + client.fetch_refs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_refs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_fetch_refs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecureSourceManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.fetch_refs + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.fetch_refs + ] = mock_rpc + + request = {} + await client.fetch_refs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_refs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + secure_source_manager.FetchRefsRequest(), + {}, + ], +) +async def test_fetch_refs_async(request_type, transport: str = "grpc_asyncio"): + client = SecureSourceManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + secure_source_manager.FetchRefsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.fetch_refs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = secure_source_manager.FetchRefsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchRefsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_refs_field_headers(): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = secure_source_manager.FetchRefsRequest() + + request.repository = "repository_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + call.return_value = secure_source_manager.FetchRefsResponse() + client.fetch_refs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "repository=repository_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_fetch_refs_field_headers_async(): + client = SecureSourceManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = secure_source_manager.FetchRefsRequest() + + request.repository = "repository_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + secure_source_manager.FetchRefsResponse() + ) + await client.fetch_refs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "repository=repository_value", + ) in kw["metadata"] + + +def test_fetch_refs_pager(transport_name: str = "grpc"): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + next_page_token="abc", + ), + secure_source_manager.FetchRefsResponse( + refs=[], + next_page_token="def", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + ], + next_page_token="ghi", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("repository", ""),)), + ) + pager = client.fetch_refs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, secure_source_manager.Ref) for i in results) + + +def test_fetch_refs_pages(transport_name: str = "grpc"): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + next_page_token="abc", + ), + secure_source_manager.FetchRefsResponse( + refs=[], + next_page_token="def", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + ], + next_page_token="ghi", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_refs(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_fetch_refs_async_pager(): + client = SecureSourceManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_refs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + next_page_token="abc", + ), + secure_source_manager.FetchRefsResponse( + refs=[], + next_page_token="def", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + ], + next_page_token="ghi", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_refs( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, secure_source_manager.Ref) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_refs_async_pages(): + client = SecureSourceManagerAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_refs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + next_page_token="abc", + ), + secure_source_manager.FetchRefsResponse( + refs=[], + next_page_token="def", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + ], + next_page_token="ghi", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.fetch_refs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + @pytest.mark.parametrize( "request_type", [ @@ -27058,6 +27506,194 @@ def test_fetch_blob_rest_required_fields( assert sorted(expected_params) == sorted(actual_params) +def test_fetch_refs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.fetch_refs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.fetch_refs] = mock_rpc + + request = {} + client.fetch_refs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_refs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_refs_rest_required_fields( + request_type=secure_source_manager.FetchRefsRequest, +): + transport_class = transports.SecureSourceManagerRestTransport + + request_init = {} + request_init["repository"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseFetchRefs, + "_BaseFetchRefs__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["repository"] = "repository_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + "type", + ) + ) + + # verify required fields with non-default values are left alone + assert "repository" in jsonified_request + assert jsonified_request["repository"] == "repository_value" + + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = secure_source_manager.FetchRefsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = secure_source_manager.FetchRefsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.fetch_refs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_refs_rest_pager(transport: str = "rest"): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + next_page_token="abc", + ), + secure_source_manager.FetchRefsResponse( + refs=[], + next_page_token="def", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + ], + next_page_token="ghi", + ), + secure_source_manager.FetchRefsResponse( + refs=[ + secure_source_manager.Ref(), + secure_source_manager.Ref(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + secure_source_manager.FetchRefsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "repository": "projects/sample1/locations/sample2/repositories/sample3" + } + + pager = client.fetch_refs(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, secure_source_manager.Ref) for i in results) + + pages = list(client.fetch_refs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_create_issue_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -31600,6 +32236,26 @@ def test_fetch_blob_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_refs_empty_call_grpc(): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + call.return_value = secure_source_manager.FetchRefsResponse() + client.fetch_refs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = secure_source_manager.FetchRefsRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_issue_empty_call_grpc(): @@ -32085,6 +32741,8 @@ async def test_get_instance_empty_call_grpc_asyncio(): state=secure_source_manager.Instance.State.CREATING, state_note=secure_source_manager.Instance.StateNote.PAUSED_CMEK_UNAVAILABLE, kms_key="kms_key_value", + satisfies_pzi=True, + satisfies_pzs=True, ) ) await client.get_instance(request=None) @@ -32907,6 +33565,32 @@ async def test_fetch_blob_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_refs_empty_call_grpc_asyncio(): + client = SecureSourceManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + secure_source_manager.FetchRefsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_refs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = secure_source_manager.FetchRefsRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -33625,6 +34309,8 @@ def test_get_instance_rest_call_success(request_type): state=secure_source_manager.Instance.State.CREATING, state_note=secure_source_manager.Instance.StateNote.PAUSED_CMEK_UNAVAILABLE, kms_key="kms_key_value", + satisfies_pzi=True, + satisfies_pzs=True, ) # Wrap the value into a proper Response obj @@ -33648,6 +34334,8 @@ def test_get_instance_rest_call_success(request_type): == secure_source_manager.Instance.StateNote.PAUSED_CMEK_UNAVAILABLE ) assert response.kms_key == "kms_key_value" + assert response.satisfies_pzi is True + assert response.satisfies_pzs is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -33788,6 +34476,8 @@ def test_create_instance_rest_call_success(request_type): "git_ssh": "git_ssh_value", }, "workforce_identity_federation_config": {"enabled": True}, + "satisfies_pzi": True, + "satisfies_pzs": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -37859,17 +38549,277 @@ def test_open_pull_request_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.open_pull_request(request) + client.open_pull_request(request) + + +@pytest.mark.parametrize( + "request_type", + [ + secure_source_manager.OpenPullRequestRequest, + dict, + ], +) +def test_open_pull_request_rest_call_success(request_type): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.open_pull_request(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_open_pull_request_rest_interceptors(null_interceptor): + transport = transports.SecureSourceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecureSourceManagerRestInterceptor(), + ) + client = SecureSourceManagerClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.SecureSourceManagerRestInterceptor, "post_open_pull_request" + ) as post, + mock.patch.object( + transports.SecureSourceManagerRestInterceptor, + "post_open_pull_request_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecureSourceManagerRestInterceptor, "pre_open_pull_request" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = secure_source_manager.OpenPullRequestRequest.pb( + secure_source_manager.OpenPullRequestRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = secure_source_manager.OpenPullRequestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.open_pull_request( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_close_pull_request_rest_bad_request( + request_type=secure_source_manager.ClosePullRequestRequest, +): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.close_pull_request(request) + + +@pytest.mark.parametrize( + "request_type", + [ + secure_source_manager.ClosePullRequestRequest, + dict, + ], +) +def test_close_pull_request_rest_call_success(request_type): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.close_pull_request(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_close_pull_request_rest_interceptors(null_interceptor): + transport = transports.SecureSourceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecureSourceManagerRestInterceptor(), + ) + client = SecureSourceManagerClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.SecureSourceManagerRestInterceptor, "post_close_pull_request" + ) as post, + mock.patch.object( + transports.SecureSourceManagerRestInterceptor, + "post_close_pull_request_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecureSourceManagerRestInterceptor, "pre_close_pull_request" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = secure_source_manager.ClosePullRequestRequest.pb( + secure_source_manager.ClosePullRequestRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = secure_source_manager.ClosePullRequestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.close_pull_request( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_pull_request_file_diffs_rest_bad_request( + request_type=secure_source_manager.ListPullRequestFileDiffsRequest, +): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_pull_request_file_diffs(request) @pytest.mark.parametrize( "request_type", [ - secure_source_manager.OpenPullRequestRequest, + secure_source_manager.ListPullRequestFileDiffsRequest, dict, ], ) -def test_open_pull_request_rest_call_success(request_type): +def test_list_pull_request_file_diffs_rest_call_success(request_type): client = SecureSourceManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -37883,153 +38833,31 @@ def test_open_pull_request_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = secure_source_manager.ListPullRequestFileDiffsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.open_pull_request(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_open_pull_request_rest_interceptors(null_interceptor): - transport = transports.SecureSourceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.SecureSourceManagerRestInterceptor(), - ) - client = SecureSourceManagerClient(transport=transport) - - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), - mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "post_open_pull_request" - ) as post, - mock.patch.object( - transports.SecureSourceManagerRestInterceptor, - "post_open_pull_request_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "pre_open_pull_request" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = secure_source_manager.OpenPullRequestRequest.pb( - secure_source_manager.OpenPullRequestRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = secure_source_manager.OpenPullRequestRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.open_pull_request( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Convert return value to protobuf type + return_value = secure_source_manager.ListPullRequestFileDiffsResponse.pb( + return_value ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_close_pull_request_rest_bad_request( - request_type=secure_source_manager.ClosePullRequestRequest, -): - client = SecureSourceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" - } - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.close_pull_request(request) - - -@pytest.mark.parametrize( - "request_type", - [ - secure_source_manager.ClosePullRequestRequest, - dict, - ], -) -def test_close_pull_request_rest_call_success(request_type): - client = SecureSourceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" - } - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.close_pull_request(request) + response = client.list_pull_request_file_diffs(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListPullRequestFileDiffsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_close_pull_request_rest_interceptors(null_interceptor): +def test_list_pull_request_file_diffs_rest_interceptors(null_interceptor): transport = transports.SecureSourceManagerRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -38041,23 +38869,24 @@ def test_close_pull_request_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "post_close_pull_request" + transports.SecureSourceManagerRestInterceptor, + "post_list_pull_request_file_diffs", ) as post, mock.patch.object( transports.SecureSourceManagerRestInterceptor, - "post_close_pull_request_with_metadata", + "post_list_pull_request_file_diffs_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "pre_close_pull_request" + transports.SecureSourceManagerRestInterceptor, + "pre_list_pull_request_file_diffs", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = secure_source_manager.ClosePullRequestRequest.pb( - secure_source_manager.ClosePullRequestRequest() + pb_message = secure_source_manager.ListPullRequestFileDiffsRequest.pb( + secure_source_manager.ListPullRequestFileDiffsRequest() ) transcode.return_value = { "method": "post", @@ -38069,19 +38898,24 @@ def test_close_pull_request_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = secure_source_manager.ListPullRequestFileDiffsResponse.to_json( + secure_source_manager.ListPullRequestFileDiffsResponse() + ) req.return_value.content = return_value - request = secure_source_manager.ClosePullRequestRequest() + request = secure_source_manager.ListPullRequestFileDiffsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = secure_source_manager.ListPullRequestFileDiffsResponse() + post_with_metadata.return_value = ( + secure_source_manager.ListPullRequestFileDiffsResponse(), + metadata, + ) - client.close_pull_request( + client.list_pull_request_file_diffs( request, metadata=[ ("key", "val"), @@ -38094,15 +38928,15 @@ def test_close_pull_request_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_pull_request_file_diffs_rest_bad_request( - request_type=secure_source_manager.ListPullRequestFileDiffsRequest, +def test_fetch_tree_rest_bad_request( + request_type=secure_source_manager.FetchTreeRequest, ): client = SecureSourceManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" + "repository": "projects/sample1/locations/sample2/repositories/sample3" } request = request_type(**request_init) @@ -38119,31 +38953,31 @@ def test_list_pull_request_file_diffs_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_pull_request_file_diffs(request) + client.fetch_tree(request) @pytest.mark.parametrize( "request_type", [ - secure_source_manager.ListPullRequestFileDiffsRequest, + secure_source_manager.FetchTreeRequest, dict, ], ) -def test_list_pull_request_file_diffs_rest_call_success(request_type): +def test_fetch_tree_rest_call_success(request_type): client = SecureSourceManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/repositories/sample3/pullRequests/sample4" + "repository": "projects/sample1/locations/sample2/repositories/sample3" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = secure_source_manager.ListPullRequestFileDiffsResponse( + return_value = secure_source_manager.FetchTreeResponse( next_page_token="next_page_token_value", ) @@ -38152,22 +38986,20 @@ def test_list_pull_request_file_diffs_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = secure_source_manager.ListPullRequestFileDiffsResponse.pb( - return_value - ) + return_value = secure_source_manager.FetchTreeResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_pull_request_file_diffs(request) + response = client.fetch_tree(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPullRequestFileDiffsPager) + assert isinstance(response, pagers.FetchTreePager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_pull_request_file_diffs_rest_interceptors(null_interceptor): +def test_fetch_tree_rest_interceptors(null_interceptor): transport = transports.SecureSourceManagerRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -38180,23 +39012,21 @@ def test_list_pull_request_file_diffs_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecureSourceManagerRestInterceptor, - "post_list_pull_request_file_diffs", + transports.SecureSourceManagerRestInterceptor, "post_fetch_tree" ) as post, mock.patch.object( transports.SecureSourceManagerRestInterceptor, - "post_list_pull_request_file_diffs_with_metadata", + "post_fetch_tree_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecureSourceManagerRestInterceptor, - "pre_list_pull_request_file_diffs", + transports.SecureSourceManagerRestInterceptor, "pre_fetch_tree" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = secure_source_manager.ListPullRequestFileDiffsRequest.pb( - secure_source_manager.ListPullRequestFileDiffsRequest() + pb_message = secure_source_manager.FetchTreeRequest.pb( + secure_source_manager.FetchTreeRequest() ) transcode.return_value = { "method": "post", @@ -38208,24 +39038,24 @@ def test_list_pull_request_file_diffs_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = secure_source_manager.ListPullRequestFileDiffsResponse.to_json( - secure_source_manager.ListPullRequestFileDiffsResponse() + return_value = secure_source_manager.FetchTreeResponse.to_json( + secure_source_manager.FetchTreeResponse() ) req.return_value.content = return_value - request = secure_source_manager.ListPullRequestFileDiffsRequest() + request = secure_source_manager.FetchTreeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = secure_source_manager.ListPullRequestFileDiffsResponse() + post.return_value = secure_source_manager.FetchTreeResponse() post_with_metadata.return_value = ( - secure_source_manager.ListPullRequestFileDiffsResponse(), + secure_source_manager.FetchTreeResponse(), metadata, ) - client.list_pull_request_file_diffs( + client.fetch_tree( request, metadata=[ ("key", "val"), @@ -38238,8 +39068,8 @@ def test_list_pull_request_file_diffs_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_tree_rest_bad_request( - request_type=secure_source_manager.FetchTreeRequest, +def test_fetch_blob_rest_bad_request( + request_type=secure_source_manager.FetchBlobRequest, ): client = SecureSourceManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -38263,17 +39093,17 @@ def test_fetch_tree_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.fetch_tree(request) + client.fetch_blob(request) @pytest.mark.parametrize( "request_type", [ - secure_source_manager.FetchTreeRequest, + secure_source_manager.FetchBlobRequest, dict, ], ) -def test_fetch_tree_rest_call_success(request_type): +def test_fetch_blob_rest_call_success(request_type): client = SecureSourceManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -38287,8 +39117,9 @@ def test_fetch_tree_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = secure_source_manager.FetchTreeResponse( - next_page_token="next_page_token_value", + return_value = secure_source_manager.FetchBlobResponse( + sha="sha_value", + content="content_value", ) # Wrap the value into a proper Response obj @@ -38296,20 +39127,21 @@ def test_fetch_tree_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = secure_source_manager.FetchTreeResponse.pb(return_value) + return_value = secure_source_manager.FetchBlobResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.fetch_tree(request) + response = client.fetch_blob(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchTreePager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, secure_source_manager.FetchBlobResponse) + assert response.sha == "sha_value" + assert response.content == "content_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_tree_rest_interceptors(null_interceptor): +def test_fetch_blob_rest_interceptors(null_interceptor): transport = transports.SecureSourceManagerRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -38322,21 +39154,21 @@ def test_fetch_tree_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "post_fetch_tree" + transports.SecureSourceManagerRestInterceptor, "post_fetch_blob" ) as post, mock.patch.object( transports.SecureSourceManagerRestInterceptor, - "post_fetch_tree_with_metadata", + "post_fetch_blob_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "pre_fetch_tree" + transports.SecureSourceManagerRestInterceptor, "pre_fetch_blob" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = secure_source_manager.FetchTreeRequest.pb( - secure_source_manager.FetchTreeRequest() + pb_message = secure_source_manager.FetchBlobRequest.pb( + secure_source_manager.FetchBlobRequest() ) transcode.return_value = { "method": "post", @@ -38348,24 +39180,24 @@ def test_fetch_tree_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = secure_source_manager.FetchTreeResponse.to_json( - secure_source_manager.FetchTreeResponse() + return_value = secure_source_manager.FetchBlobResponse.to_json( + secure_source_manager.FetchBlobResponse() ) req.return_value.content = return_value - request = secure_source_manager.FetchTreeRequest() + request = secure_source_manager.FetchBlobRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = secure_source_manager.FetchTreeResponse() + post.return_value = secure_source_manager.FetchBlobResponse() post_with_metadata.return_value = ( - secure_source_manager.FetchTreeResponse(), + secure_source_manager.FetchBlobResponse(), metadata, ) - client.fetch_tree( + client.fetch_blob( request, metadata=[ ("key", "val"), @@ -38378,8 +39210,8 @@ def test_fetch_tree_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_blob_rest_bad_request( - request_type=secure_source_manager.FetchBlobRequest, +def test_fetch_refs_rest_bad_request( + request_type=secure_source_manager.FetchRefsRequest, ): client = SecureSourceManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -38403,17 +39235,17 @@ def test_fetch_blob_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.fetch_blob(request) + client.fetch_refs(request) @pytest.mark.parametrize( "request_type", [ - secure_source_manager.FetchBlobRequest, + secure_source_manager.FetchRefsRequest, dict, ], ) -def test_fetch_blob_rest_call_success(request_type): +def test_fetch_refs_rest_call_success(request_type): client = SecureSourceManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -38427,9 +39259,8 @@ def test_fetch_blob_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = secure_source_manager.FetchBlobResponse( - sha="sha_value", - content="content_value", + return_value = secure_source_manager.FetchRefsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -38437,21 +39268,20 @@ def test_fetch_blob_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = secure_source_manager.FetchBlobResponse.pb(return_value) + return_value = secure_source_manager.FetchRefsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.fetch_blob(request) + response = client.fetch_refs(request) # Establish that the response is the type that we expect. - assert isinstance(response, secure_source_manager.FetchBlobResponse) - assert response.sha == "sha_value" - assert response.content == "content_value" + assert isinstance(response, pagers.FetchRefsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_blob_rest_interceptors(null_interceptor): +def test_fetch_refs_rest_interceptors(null_interceptor): transport = transports.SecureSourceManagerRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -38464,21 +39294,21 @@ def test_fetch_blob_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "post_fetch_blob" + transports.SecureSourceManagerRestInterceptor, "post_fetch_refs" ) as post, mock.patch.object( transports.SecureSourceManagerRestInterceptor, - "post_fetch_blob_with_metadata", + "post_fetch_refs_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecureSourceManagerRestInterceptor, "pre_fetch_blob" + transports.SecureSourceManagerRestInterceptor, "pre_fetch_refs" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = secure_source_manager.FetchBlobRequest.pb( - secure_source_manager.FetchBlobRequest() + pb_message = secure_source_manager.FetchRefsRequest.pb( + secure_source_manager.FetchRefsRequest() ) transcode.return_value = { "method": "post", @@ -38490,24 +39320,24 @@ def test_fetch_blob_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = secure_source_manager.FetchBlobResponse.to_json( - secure_source_manager.FetchBlobResponse() + return_value = secure_source_manager.FetchRefsResponse.to_json( + secure_source_manager.FetchRefsResponse() ) req.return_value.content = return_value - request = secure_source_manager.FetchBlobRequest() + request = secure_source_manager.FetchRefsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = secure_source_manager.FetchBlobResponse() + post.return_value = secure_source_manager.FetchRefsResponse() post_with_metadata.return_value = ( - secure_source_manager.FetchBlobResponse(), + secure_source_manager.FetchRefsResponse(), metadata, ) - client.fetch_blob( + client.fetch_refs( request, metadata=[ ("key", "val"), @@ -42902,6 +43732,25 @@ def test_fetch_blob_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_refs_empty_call_rest(): + client = SecureSourceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_refs), "__call__") as call: + client.fetch_refs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = secure_source_manager.FetchRefsRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_issue_empty_call_rest(): @@ -43390,6 +44239,7 @@ def test_secure_source_manager_base_transport(): "list_pull_request_file_diffs", "fetch_tree", "fetch_blob", + "fetch_refs", "create_issue", "get_issue", "list_issues", @@ -43460,7 +44310,10 @@ def test_secure_source_manager_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/securesourcemanager.read-write", + ), quota_project_id="octopus", ) @@ -43486,7 +44339,10 @@ def test_secure_source_manager_auth_adc(): SecureSourceManagerClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/securesourcemanager.read-write", + ), quota_project_id=None, ) @@ -43506,7 +44362,10 @@ def test_secure_source_manager_transport_auth_adc(transport_class): transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/securesourcemanager.read-write", + ), quota_project_id="octopus", ) @@ -43559,7 +44418,10 @@ def test_secure_source_manager_transport_create_channel(transport_class, grpc_he credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/securesourcemanager.read-write", + ), scopes=["1", "2"], default_host="securesourcemanager.googleapis.com", ssl_credentials=None, @@ -43787,6 +44649,9 @@ def test_secure_source_manager_client_transport_session_collision(transport_name session1 = client1.transport.fetch_blob._session session2 = client2.transport.fetch_blob._session assert session1 != session2 + session1 = client1.transport.fetch_refs._session + session2 = client2.transport.fetch_refs._session + assert session1 != session2 session1 = client1.transport.create_issue._session session2 = client2.transport.create_issue._session assert session1 != session2 diff --git a/packages/google-cloud-spanner-dbapi-driver/.repo-metadata.json b/packages/google-cloud-spanner-dbapi-driver/.repo-metadata.json index 6008b776651b..293f7836f3a9 100644 --- a/packages/google-cloud-spanner-dbapi-driver/.repo-metadata.json +++ b/packages/google-cloud-spanner-dbapi-driver/.repo-metadata.json @@ -1,16 +1,9 @@ { - "api_description": "Google Cloud Spanner DBAPI 2.0 Driver", - "api_id": "spanner.googleapis.com", - "api_shortname": "spanner", - "client_documentation": "https://cloud.google.com/python/docs/reference/spanner-dbapi-driver/latest", - "default_version": "v1", - "distribution_name": "google-cloud-spanner-dbapi-driver", - "issue_tracker": "https://github.com/googleapis/google-cloud-python/issues", - "language": "python", - "library_type": "MANUAL", - "name": "spanner-dbapi-driver", - "name_pretty": "Spanner DBAPI Driver", - "product_documentation": "https://cloud.google.com/spanner/", - "release_level": "preview", - "repo": "googleapis/google-cloud-python" -} + "client_documentation": "https://cloud.google.com/python/docs/reference/google-cloud-spanner-dbapi-driver/latest", + "distribution_name": "google-cloud-spanner-dbapi-driver", + "language": "python", + "library_type": "INTEGRATION", + "name": "google-cloud-spanner-dbapi-driver", + "release_level": "preview", + "repo": "googleapis/google-cloud-python" +} \ No newline at end of file diff --git a/packages/google-cloud-spanner-dbapi-driver/CHANGELOG.md b/packages/google-cloud-spanner-dbapi-driver/CHANGELOG.md new file mode 100644 index 000000000000..eeaeefeafa75 --- /dev/null +++ b/packages/google-cloud-spanner-dbapi-driver/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +[PyPI History][1] + +[1]: https://pypi.org/project/google-cloud-spanner-dbapi-driver/#history diff --git a/packages/google-cloud-spanner-dbapi-driver/docs/CHANGELOG.md b/packages/google-cloud-spanner-dbapi-driver/docs/CHANGELOG.md new file mode 120000 index 000000000000..04c99a55caae --- /dev/null +++ b/packages/google-cloud-spanner-dbapi-driver/docs/CHANGELOG.md @@ -0,0 +1 @@ +../CHANGELOG.md \ No newline at end of file diff --git a/packages/google-cloud-spanner-dbapi-driver/docs/index.rst b/packages/google-cloud-spanner-dbapi-driver/docs/index.rst index 98ebacf8044d..c150aae41bfc 100644 --- a/packages/google-cloud-spanner-dbapi-driver/docs/index.rst +++ b/packages/google-cloud-spanner-dbapi-driver/docs/index.rst @@ -13,7 +13,6 @@ Changelog For a list of all ``google-cloud-spanner-dbapi`` releases: .. toctree:: - :maxdepth: 2 + :maxdepth: 2 -.. toctree:: - :hidden: + CHANGELOG diff --git a/packages/google-cloud-spanner/.agents/workflows/verify-asyncio.md b/packages/google-cloud-spanner/.agents/workflows/verify-asyncio.md index f5887a178773..2287597792bb 100644 --- a/packages/google-cloud-spanner/.agents/workflows/verify-asyncio.md +++ b/packages/google-cloud-spanner/.agents/workflows/verify-asyncio.md @@ -25,11 +25,18 @@ nox -s system -- tests/system/_async ## 3. Verify Sync/Async Parity Run the cross-sync generation tool and ensure no regressions in the synchronous codebase. + +`generate.py` must be pointed at a **directory**; it only rewrites files reachable from +that directory that carry a `__CROSS_SYNC_OUTPUT__` annotation. ```bash -python3 .cross_sync/generate.py +PYTHONPATH=.cross_sync python3 .cross_sync/generate.py google/cloud/spanner_v1/_async/ +git diff --exit-code google/cloud/spanner_v1/ nox -s unit-3.14 nox -s system-3.14 ``` +A non-empty `git diff` here means the generated sync code has drifted from +`google/cloud/spanner_v1/_async/`. Fix it in the `_async/` source, never in the +generated artifact. ## 4. Check for Coroutine Leaks Ensure all asynchronous GAPIC calls are properly awaited. Search for any unawaited coroutines in the `_async` directory. diff --git a/packages/google-cloud-spanner/.cross_sync/generate.py b/packages/google-cloud-spanner/.cross_sync/generate.py index 3c96b7469e61..07a619e1105b 100644 --- a/packages/google-cloud-spanner/.cross_sync/generate.py +++ b/packages/google-cloud-spanner/.cross_sync/generate.py @@ -39,6 +39,56 @@ def extract_header_comments(file_path) -> str: return "".join(header) +# Keep these in sync with the `format` / `lint` sessions in noxfile.py, otherwise +# regenerating the artifacts will produce a spurious formatting-only diff. +RUFF_TARGET_VERSION = "py310" +RUFF_LINE_LENGTH = "88" + + +def format_with_ruff(source: str, filename: str) -> str: + """ + Format generated source with ruff, the formatter used by this repository. + + Runs two passes over stdin, mirroring `nox -s format`: + 1. `ruff check --select I,F401 --fix` to sort imports and drop the + imports that became unused during the async -> sync conversion. + 2. `ruff format` to apply the code style. + + Args: + source: the generated python source + filename: the path the source will be written to. Only used to give + ruff a sensible filename for diagnostics. + Returns: + the formatted source + """ + import shutil + import subprocess + import sys + + ruff = shutil.which("ruff") + base_command = [ruff] if ruff else [sys.executable, "-m", "ruff"] + shared_args = [ + f"--target-version={RUFF_TARGET_VERSION}", + "--line-length", + RUFF_LINE_LENGTH, + "--stdin-filename", + filename, + "-", + ] + passes = [ + base_command + ["check", "--select", "I,F401", "--fix", "--quiet", *shared_args], + base_command + ["format", *shared_args], + ] + for command in passes: + result = subprocess.run(command, input=source, capture_output=True, text=True) + if result.returncode != 0: + raise RuntimeError( + f"ruff failed for {filename}: {' '.join(command)}\n{result.stderr}" + ) + source = result.stdout + return source + + class CrossSyncOutputFile: def __init__(self, output_path: str, ast_tree, header: str | None = None): @@ -51,18 +101,12 @@ def render(self, with_formatter=True, save_to_disk: bool = True) -> str: Render the file to a string, and optionally save to disk Args: - with_formatter: whether to run the output through black before returning + with_formatter: whether to run the output through ruff before returning save_to_disk: whether to write the output to the file path """ full_str = self.header + ast.unparse(self.tree) if with_formatter: - import black # type: ignore - import autoflake # type: ignore - - full_str = black.format_str( - autoflake.fix_code(full_str, remove_all_unused_imports=True), - mode=black.FileMode(), - ) + full_str = format_with_ruff(full_str, self.output_path) if save_to_disk: import os os.makedirs(os.path.dirname(self.output_path), exist_ok=True) @@ -71,12 +115,18 @@ def render(self, with_formatter=True, save_to_disk: bool = True) -> str: return full_str -def convert_files_in_dir(directory: str) -> set[CrossSyncOutputFile]: +def convert_path(search_path: str) -> set[CrossSyncOutputFile]: import glob from transformers import CrossSyncFileProcessor - # find all python files in the directory - files = glob.glob(directory + "/**/*.py", recursive=True) + if os.path.isfile(search_path): + files = [search_path] + elif os.path.isdir(search_path): + files = glob.glob(search_path + "/**/*.py", recursive=True) + else: + print(f"Path does not exist: {search_path}") + sys.exit(1) + # keep track of the output files pointed to by the annotated classes artifacts: set[CrossSyncOutputFile] = set() file_transformer = CrossSyncFileProcessor() @@ -100,13 +150,22 @@ def save_artifacts(artifacts: Sequence[CrossSyncOutputFile]): if __name__ == "__main__": + import os import sys if len(sys.argv) < 2: - print("Usage: python .cross_sync/generate.py ") + print("Usage: python .cross_sync/generate.py ") sys.exit(1) search_root = sys.argv[1] - outputs = convert_files_in_dir(search_root) + if not os.path.exists(search_root): + print(f"Path does not exist: {search_root}") + sys.exit(1) + + outputs = convert_path(search_root) + if not outputs: + print(f"No __CROSS_SYNC_OUTPUT__ annotated files found under {search_root}") + sys.exit(1) + print(f"Generated {len(outputs)} artifacts: {[a.output_path for a in outputs]}") save_artifacts(outputs) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/connection.py b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/connection.py index a1570d9ca69a..d73a036b01a7 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/connection.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/connection.py @@ -820,6 +820,8 @@ def connect( instance_type=None, data_boost_enabled=False, auto_partition_mode=False, + username=None, + password=None, **kwargs, ): """Creates a connection to a Google Cloud Spanner database. @@ -909,6 +911,10 @@ def connect( :param client_key: (Optional) The path to the client key file used for mTLS connection. This is intended only for Spanner Omni endpoints. This is mandatory if Spanner Omni requires an mTLS connection. + :type username: str + :param username: (Optional) Username for Spanner Omni authentication. + :type password: str + :param password: (Optional) Password for Spanner Omni authentication. """ if client is None: client_info = ClientInfo( @@ -956,7 +962,29 @@ def connect( ) project = "default" - credentials = AnonymousCredentials() + has_username = username is not None + has_password = password is not None + if has_username != has_password: + raise ValueError( + "Both username and password must be specified for Omni authentication" + ) + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + if has_username and has_password: + credentials = SpannerOmniCredentials( + username=username, + password=password, + target=host_endpoint, + use_plain_text=use_plain_text, + ca_certificate=ca_certificate, + client_certificate=client_certificate, + client_key=client_key, + ) + else: + credentials = AnonymousCredentials() + client_options = kwargs.get("client_options") if client_options is None: client_options = ClientOptions(api_endpoint=host_endpoint) @@ -968,7 +996,6 @@ def connect( client_options = copy.copy(client_options) client_options.api_endpoint = host_endpoint - client = spanner.Client( project=project, credentials=credentials, diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/_helpers.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/_helpers.py index e02c79c6c553..6e256a4e24a5 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/_helpers.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/_helpers.py @@ -75,6 +75,7 @@ def _create_spanner_omni_transport( client_certificate, client_key, interceptors=None, + credentials=None, ): """Creates a Spanner Omni transport in async mode. @@ -87,6 +88,8 @@ def _create_spanner_omni_transport( client_certificate (str): Path to the client certificate file for mTLS. client_key (str): Path to the client key file for mTLS. interceptors (list): Optional list of interceptors to add to the channel. + credentials (google.auth.credentials.Credentials, optional): Credentials + to use for authentication. Returns: object: An instance of the transport class created by `transport_factory`. @@ -98,8 +101,25 @@ def _create_spanner_omni_transport( from google.auth.credentials import AnonymousCredentials channel = None + all_interceptors = list(interceptors) if interceptors is not None else [] + if credentials is not None: + if hasattr(credentials, "create_async_auth_interceptors"): + all_interceptors.extend(credentials.create_async_auth_interceptors()) + elif hasattr(credentials, "create_async_auth_interceptor"): + res = credentials.create_async_auth_interceptor() + if isinstance(res, (list, tuple)): + all_interceptors.extend(res) + else: + all_interceptors.append(res) + elif hasattr(credentials, "create_auth_interceptor"): + res = credentials.create_auth_interceptor(is_async=True) + if isinstance(res, (list, tuple)): + all_interceptors.extend(res) + else: + all_interceptors.append(res) + if use_plain_text: - channel = grpc.aio.insecure_channel(target=host, interceptors=interceptors) + channel = grpc.aio.insecure_channel(target=host, interceptors=all_interceptors) elif ca_certificate: with open(ca_certificate, "rb") as f: ca_cert = f.read() @@ -119,12 +139,17 @@ def _create_spanner_omni_transport( ) else: ssl_creds = grpc.ssl_channel_credentials(root_certificates=ca_cert) - channel = grpc.aio.secure_channel(host, ssl_creds, interceptors=interceptors) + channel = grpc.aio.secure_channel( + host, ssl_creds, interceptors=all_interceptors + ) else: raise ValueError( "TLS/mTLS connection requires ca_certificate to be set for Spanner Omni" ) - return transport_factory(channel=channel, credentials=AnonymousCredentials()) + actual_credentials = ( + credentials if credentials is not None else AnonymousCredentials() + ) + return transport_factory(channel=channel, credentials=actual_credentials) def _create_experimental_host_transport( diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py index 2e7da9fe808a..a18bbc9c605a 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py @@ -302,6 +302,8 @@ def __init__( client_certificate=None, client_key=None, instance_type=None, + username=None, + password=None, ): self._emulator_host = _get_spanner_emulator_host() self._use_plain_text = use_plain_text @@ -353,10 +355,37 @@ def __init__( self._ca_certificate = ca_certificate self._client_certificate = client_certificate self._client_key = client_key - credentials = AnonymousCredentials() + self._host = host_endpoint + has_username = username is not None + has_password = password is not None + if has_username != has_password: + raise ValueError( + "Both username and password must be specified for Omni authentication" + ) + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + if has_username and has_password: + credentials = SpannerOmniCredentials( + username=username, + password=password, + target=host_endpoint, + use_plain_text=use_plain_text, + ca_certificate=ca_certificate, + client_certificate=client_certificate, + client_key=client_key, + ) + elif not isinstance(credentials, SpannerOmniCredentials): + credentials = AnonymousCredentials() disable_builtin_metrics = True elif isinstance(credentials, AnonymousCredentials): self._emulator_host = self._client_options.api_endpoint + else: + if username is not None or password is not None: + raise ValueError( + "username and password can only be used when instance_type='omni'." + ) # NOTE: This API has no use for the _http argument, but sending it # will have no impact since the _http() @property only lazily @@ -509,6 +538,7 @@ def instance_admin_api(self): self._ca_certificate, self._client_certificate, self._client_key, + credentials=self.credentials, ) else: @@ -519,6 +549,7 @@ def instance_admin_api(self): self._ca_certificate, self._client_certificate, self._client_key, + credentials=self.credentials, ) self._instance_admin_api = InstanceAdminClient( @@ -567,6 +598,7 @@ def database_admin_api(self): self._ca_certificate, self._client_certificate, self._client_key, + credentials=self.credentials, ) else: @@ -577,6 +609,7 @@ def database_admin_api(self): self._ca_certificate, self._client_certificate, self._client_key, + credentials=self.credentials, ) self._database_admin_api = DatabaseAdminClient( diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/database.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/database.py index e12c639eca3b..c12769172c23 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/database.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/database.py @@ -513,6 +513,7 @@ def spanner_api(self): client._ca_certificate, client._client_certificate, client._client_key, + credentials=client.credentials, ) else: transport = _create_spanner_omni_transport_sync( @@ -522,6 +523,7 @@ def spanner_api(self): client._ca_certificate, client._client_certificate, client._client_key, + credentials=client.credentials, ) self._spanner_api = SpannerClient( client_info=client_info, diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/snapshot.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/snapshot.py index b54b5d314e1a..5e64e106db99 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/snapshot.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/snapshot.py @@ -68,6 +68,10 @@ "Received unexpected EOS on DATA frame from server", ) +# Maximum time that a request will wait for a concurrent request to begin the +# transaction before giving up. +_TRANSACTION_BEGIN_TIMEOUT_SECONDS = 30.0 + @CrossSync.convert async def _restart_on_unavailable( @@ -221,10 +225,20 @@ def __init__(self, session, client_context=None): self._client_context = _validate_client_context(client_context) self._execute_sql_request_count: int = 0 self._read_request_count: int = 0 + self._begin_request_sent: bool = False + + # Identifier for the transaction. self._transaction_id: Optional[bytes] = None self._precommit_token: Optional[MultiplexedSessionPrecommitToken] = None + + # Operations within a transaction can be performed concurrently, so we + # need to use a lock when updating the transaction. self._lock: CrossSync.Lock = CrossSync.Lock() + # Event to coordinate concurrent requests beginning the transaction. + # This is used to prevent the "Transaction has not begun" race condition. + self._transaction_begin_event: CrossSync.Event = CrossSync.Event() + @property def _resource_info(self): """Resource information for metrics labels.""" @@ -235,6 +249,39 @@ def _resource_info(self): "database": database.database_id, } + @CrossSync.convert + async def _wait_for_transaction_begin(self) -> None: + """Claims the inline-begin for this request, or waits for it to complete. + + The first request against the transaction is the one that begins it + inline. Requests that are issued concurrently, before the transaction + id is available, must wait for that first request to complete instead + of assuming that the transaction has not begun. + + :raises ValueError: if the transaction has already been used to execute + a request, but is not a multi-use transaction, or if the concurrent + request that began the transaction did not complete in time. + """ + + async with self._lock: + if self._begin_request_sent or self._read_request_count > 0: + if not self._multi_use: + raise ValueError("Cannot re-use single-use snapshot.") + wait_needed = self._transaction_id is None + else: + wait_needed = False + self._begin_request_sent = True + + if not wait_needed: + return + + await CrossSync.event_wait( + self._transaction_begin_event, + timeout=_TRANSACTION_BEGIN_TIMEOUT_SECONDS, + ) + if not self._transaction_begin_event.is_set(): + raise ValueError("Timed out waiting for transaction to begin.") + @CrossSync.convert async def begin(self) -> bytes: """Begins a transaction on the database. @@ -246,7 +293,6 @@ async def begin(self) -> bytes: """ return await self._begin_transaction() - @CrossSync.convert @CrossSync.convert async def read( self, @@ -265,12 +311,88 @@ async def read( column_info=None, lazy_decode=False, ): - """Perform a ``StreamingRead`` API request for rows in a table.""" - if self._read_request_count > 0: - if not self._multi_use: - raise ValueError("Cannot re-use single-use snapshot.") - if self._transaction_id is None: - raise ValueError("Transaction has not begun.") + """Perform a ``StreamingRead`` API request for rows in a table. + + :type table: str + :param table: name of the table from which to fetch data + + :type columns: list of str + :param columns: names of columns to be retrieved + + :type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet` + :param keyset: keys / ranges identifying rows to be retrieved + + :type index: str + :param index: (Optional) name of index to use, rather than the + table's primary key + + :type limit: int + :param limit: (Optional) maximum number of rows to return. + Incompatible with ``partition``. + + :type partition: bytes + :param partition: (Optional) one of the partition tokens returned + from :meth:`partition_read`. Incompatible with + ``limit``. + + :type request_options: + :class:`google.cloud.spanner_v1.types.RequestOptions` + :param request_options: + (Optional) Common options for this request. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.RequestOptions`. + Please note, the `transactionTag` setting will be ignored for + snapshot as it's not supported for read-only transactions. + + :type retry: :class:`~google.api_core.retry.Retry` + :param retry: (Optional) The retry settings for this request. + + :type timeout: float + :param timeout: (Optional) The timeout for this request. + + :type data_boost_enabled: + :param data_boost_enabled: + (Optional) If this is for a partitioned read and this field is + set ``true``, the request will be executed via offline access. + If the field is set to ``true`` but the request does not set + ``partition_token``, the API will return an + ``INVALID_ARGUMENT`` error. + + :type directed_read_options: :class:`~google.cloud.spanner_v1.DirectedReadOptions` + or :class:`dict` + :param directed_read_options: (Optional) Request level option used to set the directed_read_options + for all ReadRequests and ExecuteSqlRequests that indicates which replicas + or regions should be used for non-transactional reads or queries. + + :type column_info: dict + :param column_info: (Optional) dict of mapping between column names and additional column information. + An object where column names as keys and custom objects as corresponding + values for deserialization. It's specifically useful for data types like + protobuf where deserialization logic is on user-specific code. When provided, + the custom object enables deserialization of backend-received column data. + If not provided, data remains serialized as bytes for Proto Messages and + integer for Proto Enums. + + :type lazy_decode: bool + :param lazy_decode: + (Optional) If this argument is set to ``true``, the iterator + returns the underlying protobuf values instead of decoded Python + objects. This reduces the time that is needed to iterate through + large result sets. The application is responsible for decoding + the data that is needed. The returned row iterator contains two + functions that can be used for this. ``iterator.decode_row(row)`` + decodes all the columns in the given row to an array of Python + objects. ``iterator.decode_column(row, column_index)`` decodes one + specific column in the given row. + + :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet` + :returns: a result set instance which can be used to consume rows. + + :raises ValueError: if the Transaction already used to execute a + read request, but is not a multi-use transaction or has not begun. + """ + + await self._wait_for_transaction_begin() session = self._session database = session._database @@ -336,7 +458,6 @@ async def read( lazy_decode=lazy_decode, ) - @CrossSync.convert @CrossSync.convert async def execute_sql( self, @@ -355,12 +476,107 @@ async def execute_sql( column_info=None, lazy_decode=False, ): - """Perform an ``ExecuteStreamingSql`` API request.""" - if self._read_request_count > 0: - if not self._multi_use: - raise ValueError("Cannot re-use single-use snapshot.") - if self._transaction_id is None: - raise ValueError("Transaction has not begun.") + """Perform an ``ExecuteStreamingSql`` API request. + + :type sql: str + :param sql: SQL query statement + + :type params: dict, {str -> column value} + :param params: values for parameter replacement. Keys must match + the names used in ``sql``. + + :type param_types: dict[str -> Union[dict, .types.Type]] + :param param_types: + (Optional) maps explicit types for one or more param values; + required if parameters are passed. + + :type query_mode: + :class:`~google.cloud.spanner_v1.types.ExecuteSqlRequest.QueryMode` + :param query_mode: Mode governing return of results / query plan. + See: + `QueryMode `_. + + :type query_options: + :class:`~google.cloud.spanner_v1.types.ExecuteSqlRequest.QueryOptions` + or :class:`dict` + :param query_options: + (Optional) Query optimizer configuration to use for the given query. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.QueryOptions` + + :type request_options: + :class:`google.cloud.spanner_v1.types.RequestOptions` + :param request_options: + (Optional) Common options for this request. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.RequestOptions`. + + :type last_statement: bool + :param last_statement: + If set to true, this option marks the end of the transaction. The + transaction should be committed or aborted after this statement + executes, and attempts to execute any other requests against this + transaction (including reads and queries) will be rejected. Mixing + mutations with statements that are marked as the last statement is + not allowed. + For DML statements, setting this option may cause some error + reporting to be deferred until commit time (e.g. validation of + unique constraints). Given this, successful execution of a DML + statement should not be assumed until the transaction commits. + + :type partition: bytes + :param partition: (Optional) one of the partition tokens returned + from :meth:`partition_query`. + + :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet` + :returns: a result set instance which can be used to consume rows. + + :type retry: :class:`~google.api_core.retry.Retry` + :param retry: (Optional) The retry settings for this request. + + :type timeout: float + :param timeout: (Optional) The timeout for this request. + + :type data_boost_enabled: + :param data_boost_enabled: + (Optional) If this is for a partitioned query and this field is + set ``true``, the request will be executed via offline access. + If the field is set to ``true`` but the request does not set + ``partition_token``, the API will return an + ``INVALID_ARGUMENT`` error. + + :type directed_read_options: :class:`~google.cloud.spanner_v1.DirectedReadOptions` + or :class:`dict` + :param directed_read_options: (Optional) Request level option used to set the directed_read_options + for all ReadRequests and ExecuteSqlRequests that indicates which replicas + or regions should be used for non-transactional reads or queries. + + :type column_info: dict + :param column_info: (Optional) dict of mapping between column names and additional column information. + An object where column names as keys and custom objects as corresponding + values for deserialization. It's specifically useful for data types like + protobuf where deserialization logic is on user-specific code. When provided, + the custom object enables deserialization of backend-received column data. + If not provided, data remains serialized as bytes for Proto Messages and + integer for Proto Enums. + + :type lazy_decode: bool + :param lazy_decode: + (Optional) If this argument is set to ``true``, the iterator + returns the underlying protobuf values instead of decoded Python + objects. This reduces the time that is needed to iterate through + large result sets. The application is responsible for decoding + the data that is needed. The returned row iterator contains two + functions that can be used for this. ``iterator.decode_row(row)`` + decodes all the columns in the given row to an array of Python + objects. ``iterator.decode_column(row, column_index)`` decodes one + specific column in the given row. + + :raises ValueError: if the Transaction already used to execute a + read request, but is not a multi-use transaction or has not begun. + """ + + await self._wait_for_transaction_begin() if params is not None: params_pb = Struct( @@ -766,6 +982,8 @@ def _update_for_transaction_pb(self, transaction_pb: Transaction) -> None: """Updates the snapshot for the given transaction.""" if self._transaction_id is None and transaction_pb.id: self._transaction_id = transaction_pb.id + # Release any request waiting for this transaction to begin. + self._transaction_begin_event.set() if transaction_pb._pb.HasField("precommit_token"): self._update_for_precommit_token_pb_unsafe(transaction_pb.precommit_token) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/streamed.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/streamed.py index c47cc0ef0a17..95fda33f7b12 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/streamed.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/streamed.py @@ -123,6 +123,11 @@ def _merge_chunk(self, value): def _merge_values(self, values): """Merge values into rows. + Note: We manually check value.HasField("null_value") here instead of + wrapping every decoder in _parse_nullable to avoid the overhead of + an extra Python function call layer for every cell value decoded in this loop. + If the nullable check logic is updated in _parse_nullable, update this check. + :type values: list of :class:`~google.protobuf.struct_pb2.Value` :param values: non-chunked values from partial result set. """ diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/testing/database_test.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/testing/database_test.py index 59e99c51419c..d2c433eba4c9 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/testing/database_test.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/testing/database_test.py @@ -138,6 +138,7 @@ def spanner_api(self): client._client_certificate, client._client_key, self._interceptors, + credentials=client.credentials, ) else: transport = _create_spanner_omni_transport_sync( @@ -148,6 +149,7 @@ def spanner_api(self): client._client_certificate, client._client_key, self._interceptors, + credentials=client.credentials, ) self._spanner_api = SpannerClient( client_info=client_info, diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/transaction.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/transaction.py index a551c6be2bfd..425857e45095 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/transaction.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/transaction.py @@ -543,49 +543,50 @@ async def execute_update( is_inline_begin = True await self._lock.acquire() - execute_sql_request = ExecuteSqlRequest( - session=session.name, - transaction=self._build_transaction_selector_pb(), - sql=dml, - params=params_pb, - param_types=param_types, - query_mode=query_mode, - query_options=query_options, - seqno=seqno, - request_options=request_options, - last_statement=last_statement, - ) + try: + execute_sql_request = ExecuteSqlRequest( + session=session.name, + transaction=self._build_transaction_selector_pb(), + sql=dml, + params=params_pb, + param_types=param_types, + query_mode=query_mode, + query_options=query_options, + seqno=seqno, + request_options=request_options, + last_statement=last_statement, + ) - nth_request = database._next_nth_request - attempt = AtomicCounter(0) + nth_request = database._next_nth_request + attempt = AtomicCounter(0) - async def wrapped_method(*args, **kwargs): - attempt.increment() - call_metadata, error_augmenter = database.with_error_augmentation( - nth_request, attempt.value, metadata - ) - execute_sql_method = functools.partial( - api.execute_sql, - request=execute_sql_request, - metadata=call_metadata, - retry=retry, - timeout=timeout, - ) - with error_augmenter: - return await execute_sql_method(*args, **kwargs) - - result_set_pb: ResultSet = await self._execute_request( - wrapped_method, - execute_sql_request, - metadata, - f"CloudSpanner.{type(self).__name__}.execute_update", - trace_attributes, - ) + async def wrapped_method(*args, **kwargs): + attempt.increment() + call_metadata, error_augmenter = database.with_error_augmentation( + nth_request, attempt.value, metadata + ) + execute_sql_method = functools.partial( + api.execute_sql, + request=execute_sql_request, + metadata=call_metadata, + retry=retry, + timeout=timeout, + ) + with error_augmenter: + return await execute_sql_method(*args, **kwargs) - self._update_for_result_set_pb(result_set_pb) + result_set_pb: ResultSet = await self._execute_request( + wrapped_method, + execute_sql_request, + metadata, + f"CloudSpanner.{type(self).__name__}.execute_update", + trace_attributes, + ) - if is_inline_begin: - self._lock.release() + self._update_for_result_set_pb(result_set_pb) + finally: + if is_inline_begin: + self._lock.release() if result_set_pb._pb.HasField("precommit_token"): await self._update_for_precommit_token_pb(result_set_pb.precommit_token) @@ -703,45 +704,46 @@ async def batch_update( is_inline_begin = True await self._lock.acquire() - execute_batch_dml_request = ExecuteBatchDmlRequest( - session=session.name, - transaction=self._build_transaction_selector_pb(), - statements=parsed, - seqno=seqno, - request_options=request_options, - last_statements=last_statement, - ) + try: + execute_batch_dml_request = ExecuteBatchDmlRequest( + session=session.name, + transaction=self._build_transaction_selector_pb(), + statements=parsed, + seqno=seqno, + request_options=request_options, + last_statements=last_statement, + ) - nth_request = database._next_nth_request - attempt = AtomicCounter(0) + nth_request = database._next_nth_request + attempt = AtomicCounter(0) - async def wrapped_method(*args, **kwargs): - attempt.increment() - call_metadata, error_augmenter = database.with_error_augmentation( - nth_request, attempt.value, metadata - ) - execute_batch_dml_method = functools.partial( - api.execute_batch_dml, - request=execute_batch_dml_request, - metadata=call_metadata, - retry=retry, - timeout=timeout, - ) - with error_augmenter: - return await execute_batch_dml_method(*args, **kwargs) - - response_pb: ExecuteBatchDmlResponse = await self._execute_request( - wrapped_method, - execute_batch_dml_request, - metadata, - "CloudSpanner.DMLTransaction", - trace_attributes, - ) + async def wrapped_method(*args, **kwargs): + attempt.increment() + call_metadata, error_augmenter = database.with_error_augmentation( + nth_request, attempt.value, metadata + ) + execute_batch_dml_method = functools.partial( + api.execute_batch_dml, + request=execute_batch_dml_request, + metadata=call_metadata, + retry=retry, + timeout=timeout, + ) + with error_augmenter: + return await execute_batch_dml_method(*args, **kwargs) - self._update_for_execute_batch_dml_response_pb(response_pb) + response_pb: ExecuteBatchDmlResponse = await self._execute_request( + wrapped_method, + execute_batch_dml_request, + metadata, + "CloudSpanner.DMLTransaction", + trace_attributes, + ) - if is_inline_begin: - self._lock.release() + self._update_for_execute_batch_dml_response_pb(response_pb) + finally: + if is_inline_begin: + self._lock.release() if ( len(response_pb.result_sets) > 0 diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py index 06b137db1e28..a9740883afa4 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py @@ -1044,6 +1044,7 @@ def _create_spanner_omni_transport( client_certificate, client_key, interceptors=None, + credentials=None, ): """Creates a Spanner Omni transport. @@ -1056,6 +1057,8 @@ def _create_spanner_omni_transport( client_certificate (str): Path to the client certificate file for mTLS. client_key (str): Path to the client key file for mTLS. interceptors (list): Optional list of interceptors to add to the channel. + credentials (google.auth.credentials.Credentials, optional): Credentials + to use for authentication (e.g. `SpannerOmniCredentials`). Returns: object: An instance of the transport class created by `transport_factory`. @@ -1067,6 +1070,10 @@ def _create_spanner_omni_transport( from google.auth.credentials import AnonymousCredentials channel = None + all_interceptors = list(interceptors) if interceptors is not None else [] + if credentials is not None and hasattr(credentials, "create_auth_interceptor"): + all_interceptors.append(credentials.create_auth_interceptor()) + if use_plain_text: channel = grpc.insecure_channel(target=host) elif ca_certificate: @@ -1093,9 +1100,12 @@ def _create_spanner_omni_transport( raise ValueError( "TLS/mTLS connection requires ca_certificate to be set for Spanner Omni" ) - if interceptors is not None: - channel = grpc.intercept_channel(channel, *interceptors) - return transport_factory(channel=channel, credentials=AnonymousCredentials()) + if all_interceptors: + channel = grpc.intercept_channel(channel, *all_interceptors) + actual_credentials = ( + credentials if credentials is not None else AnonymousCredentials() + ) + return transport_factory(channel=channel, credentials=actual_credentials) def _create_experimental_host_transport( diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/batch.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/batch.py index c32b65812db4..c0ff1cc1a613 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/batch.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/batch.py @@ -58,8 +58,7 @@ class _BatchBase(_SessionWrapper): """Accumulate mutations for transmission during :meth:`commit`. :type session: :class:`~google.cloud.spanner_v1.session.Session` - :param session: the session used to perform the commit - """ + :param session: the session used to perform the commit""" def __init__(self, session, client_context=None): super(_BatchBase, self).__init__(session) @@ -158,14 +157,12 @@ def send(self, queue, key, payload=None, deliver_time=None): :param payload: (Optional) The payload of the message. :type deliver_time: :class:`datetime.datetime` - :param deliver_time: (Optional) The time at which Spanner will begin attempting to deliver the message. - """ + :param deliver_time: (Optional) The time at which Spanner will begin attempting to deliver the message.""" send_kwargs = {"queue": queue, "key": _make_list_value_pb(key)} if payload is not None: send_kwargs["payload"] = _make_value_pb(payload) if deliver_time is not None: send_kwargs["deliver_time"] = _datetime_to_pb_timestamp(deliver_time) - send = Mutation.Send(**send_kwargs) self._mutations.append(Mutation(send=send)) @@ -179,12 +176,10 @@ def ack(self, queue, key, ignore_not_found=None): :param key: The primary key of the message to be acked. :type ignore_not_found: bool - :param ignore_not_found: (Optional) Whether to ignore if the message does not exist. - """ + :param ignore_not_found: (Optional) Whether to ignore if the message does not exist.""" ack_kwargs = {"queue": queue, "key": _make_list_value_pb(key)} if ignore_not_found is not None: ack_kwargs["ignore_not_found"] = ignore_not_found - ack = Mutation.Ack(**ack_kwargs) self._mutations.append(Mutation(ack=ack)) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py index 83bde6d89ccc..7ae7f58a0e0d 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py @@ -267,6 +267,8 @@ def __init__( client_certificate=None, client_key=None, instance_type=None, + username=None, + password=None, ): self._emulator_host = _get_spanner_emulator_host() self._use_plain_text = use_plain_text @@ -279,7 +281,6 @@ def __init__( ) else: self._client_options = client_options - host_endpoint = None if experimental_host is not None: warnings.warn( @@ -289,13 +290,11 @@ def __init__( ) instance_type = "omni" host_endpoint = experimental_host - if instance_type is not None: instance_type = instance_type.lower() if instance_type not in ("cloud", "omni"): raise ValueError("instance_type must be one of 'cloud' or 'omni'") self._instance_type = instance_type - if self._emulator_host: credentials = AnonymousCredentials() elif self._instance_type == "omni": @@ -305,21 +304,46 @@ def __init__( host_endpoint = self._client_options.api_endpoint elif isinstance(self._client_options, dict): host_endpoint = self._client_options.get("api_endpoint") - if not host_endpoint: raise ValueError( "Host must be set for connecting to Spanner Omni instances" ) - project = "default" self._use_plain_text = use_plain_text self._ca_certificate = ca_certificate self._client_certificate = client_certificate self._client_key = client_key - credentials = AnonymousCredentials() + self._host = host_endpoint + has_username = username is not None + has_password = password is not None + if has_username != has_password: + raise ValueError( + "Both username and password must be specified for Omni authentication" + ) + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + if has_username and has_password: + credentials = SpannerOmniCredentials( + username=username, + password=password, + target=host_endpoint, + use_plain_text=use_plain_text, + ca_certificate=ca_certificate, + client_certificate=client_certificate, + client_key=client_key, + ) + elif not isinstance(credentials, SpannerOmniCredentials): + credentials = AnonymousCredentials() disable_builtin_metrics = True elif isinstance(credentials, AnonymousCredentials): self._emulator_host = self._client_options.api_endpoint + else: + if username is not None or password is not None: + raise ValueError( + "username and password can only be used when instance_type='omni'." + ) super(Client, self).__init__( project=project, credentials=credentials, @@ -443,6 +467,7 @@ def instance_admin_api(self): self._ca_certificate, self._client_certificate, self._client_key, + credentials=self.credentials, ) self._instance_admin_api = InstanceAdminClient( client_info=self._client_info, @@ -481,6 +506,7 @@ def database_admin_api(self): self._ca_certificate, self._client_certificate, self._client_key, + credentials=self.credentials, ) self._database_admin_api = DatabaseAdminClient( client_info=self._client_info, @@ -518,8 +544,7 @@ def default_transaction_options(self): :rtype: :class:`~google.cloud.spanner_v1.DefaultTransactionOptions` or :class:`dict` - :returns: The default transaction options that are used by this client for all transactions. - """ + :returns: The default transaction options that are used by this client for all transactions.""" return self._default_transaction_options @property diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/database.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/database.py index f98d6d09f70d..0508e0ae23c8 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/database.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/database.py @@ -42,9 +42,7 @@ RestoreDatabaseRequest, UpdateDatabaseDdlRequest, ) -from google.cloud.spanner_admin_database_v1 import ( - Database as DatabasePB, -) +from google.cloud.spanner_admin_database_v1 import Database as DatabasePB from google.cloud.spanner_admin_database_v1.types import DatabaseDialect from google.cloud.spanner_v1._helpers import ( _augment_errors_with_request_id, @@ -149,8 +147,7 @@ class Database(object): has drop protection enabled or not. :type proto_descriptors: bytes :param proto_descriptors: (Optional) Proto descriptors used by CREATE/ALTER PROTO BUNDLE - statements in 'ddl_statements' above. - """ + statements in 'ddl_statements' above.""" _spanner_api: SpannerClient = None __transport_lock = threading.Lock() @@ -452,6 +449,7 @@ def spanner_api(self): client._ca_certificate, client._client_certificate, client._client_key, + credentials=client.credentials, ) self._spanner_api = SpannerClient( client_info=client_info, @@ -720,8 +718,7 @@ def drop(self): """Drop this database. See - https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase - """ + https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase""" api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) api.drop_database( @@ -1114,8 +1111,7 @@ def is_ready(self): """Test whether this database is ready for use. :rtype: bool - :returns: True if the database state is READY_OPTIMIZING or READY, else False. - """ + :returns: True if the database state is READY_OPTIMIZING or READY, else False.""" return ( self.state == DatabasePB.State.READY_OPTIMIZING or self.state == DatabasePB.State.READY diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/database_sessions_manager.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/database_sessions_manager.py index 1b2c6231f46e..79862d90e44d 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/database_sessions_manager.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/database_sessions_manager.py @@ -130,7 +130,6 @@ def _get_multiplexed_session(self) -> Session: session = self._multiplexed_session if session is not None: return session - with self._init_lock: if self._multiplexed_session_lock is None: self._multiplexed_session_lock = CrossSync._Sync_Impl.Lock() @@ -188,23 +187,19 @@ def _rotate_multiplexed_session(self) -> bool: """Rotates the multiplexed session by building and swapping in a new session. :rtype: bool - :returns: True if the session was successfully refreshed, False otherwise. - """ + :returns: True if the session was successfully refreshed, False otherwise.""" try: new_session = self._build_multiplexed_session() except Exception: return False - with self._multiplexed_session_lock: old_session = self._multiplexed_session self._multiplexed_session = new_session - if old_session is not None: try: CrossSync._Sync_Impl.run_if_async(old_session.delete) except Exception: pass - return True @staticmethod @@ -239,11 +234,9 @@ def _maintain_multiplexed_session(session_manager_ref) -> None: session_created_time = time.monotonic() manager = None continue - manager = None CrossSync._Sync_Impl.event_wait( - terminate_event, - timeout=polling_interval_seconds, + terminate_event, timeout=polling_interval_seconds ) @classmethod diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/instance.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/instance.py index 5fb824886d82..8e5a6b2bac91 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/instance.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/instance.py @@ -114,8 +114,7 @@ class Instance(object): :param labels: (Optional) User-assigned labels for this instance. :type experimental_host: str - :param experimental_host: (Deprecated) The instance type and host are now managed by the Client. - """ + :param experimental_host: (Deprecated) The instance type and host are now managed by the Client.""" def __init__( self, diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/__init__.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/__init__.py new file mode 100644 index 000000000000..d295009a12c4 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/__init__.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Spanner Omni authentication and connection utilities.""" + +from google.cloud.spanner_v1.omni.credentials import SpannerOmniCredentials +from google.cloud.spanner_v1.omni.login_client import LoginClient +from google.cloud.spanner_v1.omni.opaque import UserAuthenticator + +__all__ = ( + "LoginClient", + "SpannerOmniCredentials", + "UserAuthenticator", +) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/credentials.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/credentials.py new file mode 100644 index 000000000000..3c966d6821d5 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/credentials.py @@ -0,0 +1,404 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Credentials implementation for Spanner Omni using OPAQUE login authentication.""" + +from __future__ import annotations + +import asyncio +import base64 +import datetime +import logging +import threading +from collections import namedtuple +from typing import Any, Callable, MutableMapping, Optional, Sequence + +import google.auth.credentials +import grpc +import grpc.aio + +from google.cloud.spanner_v1.omni.login_client import LoginClient + +_LOGGER = logging.getLogger(__name__) + + +class _ClientCallDetails( + namedtuple( + "_ClientCallDetails", + ["method", "timeout", "metadata", "credentials", "wait_for_ready"], + ), + grpc.ClientCallDetails, +): + pass + + +class _OmniAuthInterceptor( + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, +): + """gRPC client interceptor that automatically attaches Spanner Omni Bearer tokens.""" + + def __init__(self, credentials: SpannerOmniCredentials) -> None: + self._credentials = credentials + + def _add_metadata( + self, client_call_details: grpc.ClientCallDetails + ) -> grpc.ClientCallDetails: + if not self._credentials.valid: + self._credentials.refresh() + token = self._credentials.token + metadata = list(client_call_details.metadata or []) + metadata.append(("authorization", f"Bearer {token}")) + + return _ClientCallDetails( + method=client_call_details.method, + timeout=client_call_details.timeout, + metadata=metadata, + credentials=client_call_details.credentials, + wait_for_ready=getattr(client_call_details, "wait_for_ready", None), + ) + + def intercept_unary_unary( + self, + continuation: Callable, + client_call_details: grpc.ClientCallDetails, + request: Any, + ) -> Any: + return continuation(self._add_metadata(client_call_details), request) + + def intercept_unary_stream( + self, + continuation: Callable, + client_call_details: grpc.ClientCallDetails, + request: Any, + ) -> Any: + return continuation(self._add_metadata(client_call_details), request) + + def intercept_stream_unary( + self, + continuation: Callable, + client_call_details: grpc.ClientCallDetails, + request_iterator: Any, + ) -> Any: + return continuation(self._add_metadata(client_call_details), request_iterator) + + def intercept_stream_stream( + self, + continuation: Callable, + client_call_details: grpc.ClientCallDetails, + request_iterator: Any, + ) -> Any: + return continuation(self._add_metadata(client_call_details), request_iterator) + + +class _AsyncClientCallDetails( + namedtuple( + "_AsyncClientCallDetails", + ["method", "timeout", "metadata", "credentials", "wait_for_ready"], + ), + grpc.aio.ClientCallDetails, +): + pass + + +class _AsyncBaseAuthInterceptor: + """Base helper for async auth interceptors.""" + + def __init__(self, credentials: SpannerOmniCredentials) -> None: + self._credentials = credentials + + async def _add_metadata( + self, client_call_details: grpc.aio.ClientCallDetails + ) -> grpc.aio.ClientCallDetails: + if not self._credentials.valid: + loop = asyncio.get_running_loop() + await loop.run_in_executor(None, self._credentials.refresh) + token = self._credentials.token + metadata = list(client_call_details.metadata or []) + metadata.append(("authorization", f"Bearer {token}")) + + return _AsyncClientCallDetails( + method=client_call_details.method, + timeout=client_call_details.timeout, + metadata=metadata, + credentials=client_call_details.credentials, + wait_for_ready=getattr(client_call_details, "wait_for_ready", None), + ) + + +class _AsyncUnaryUnaryAuthInterceptor( + _AsyncBaseAuthInterceptor, grpc.aio.UnaryUnaryClientInterceptor +): + """Async gRPC interceptor for unary-unary calls.""" + + async def intercept_unary_unary( + self, + continuation: Callable, + client_call_details: grpc.aio.ClientCallDetails, + request: Any, + ) -> Any: + return await continuation( + await self._add_metadata(client_call_details), request + ) + + +class _AsyncUnaryStreamAuthInterceptor( + _AsyncBaseAuthInterceptor, grpc.aio.UnaryStreamClientInterceptor +): + """Async gRPC interceptor for unary-stream calls.""" + + async def intercept_unary_stream( + self, + continuation: Callable, + client_call_details: grpc.aio.ClientCallDetails, + request: Any, + ) -> Any: + return await continuation( + await self._add_metadata(client_call_details), request + ) + + +class _AsyncStreamUnaryAuthInterceptor( + _AsyncBaseAuthInterceptor, grpc.aio.StreamUnaryClientInterceptor +): + """Async gRPC interceptor for stream-unary calls.""" + + async def intercept_stream_unary( + self, + continuation: Callable, + client_call_details: grpc.aio.ClientCallDetails, + request_iterator: Any, + ) -> Any: + return await continuation( + await self._add_metadata(client_call_details), request_iterator + ) + + +class _AsyncStreamStreamAuthInterceptor( + _AsyncBaseAuthInterceptor, grpc.aio.StreamStreamClientInterceptor +): + """Async gRPC interceptor for stream-stream calls.""" + + async def intercept_stream_stream( + self, + continuation: Callable, + client_call_details: grpc.aio.ClientCallDetails, + request_iterator: Any, + ) -> Any: + return await continuation( + await self._add_metadata(client_call_details), request_iterator + ) + + +class SpannerOmniCredentials(google.auth.credentials.Credentials): + """Credentials for Spanner Omni authentication using the OPAQUE protocol. + + Args: + username (str): The username for login. + password (str | bytes): The password for login. + target (str): The endpoint / target address for Spanner Omni. + use_plain_text (bool): Whether to use an insecure (plaintext) connection. + ca_certificate (str, optional): Path to the root CA certificate file. + client_certificate (str, optional): Path to the client certificate file for mTLS. + client_key (str, optional): Path to the client private key file for mTLS. + ssl_credentials (grpc.ChannelCredentials, optional): Pre-constructed SSL channel credentials. + """ + + def __init__( + self, + username: str, + password: str | bytes, + target: str, + use_plain_text: bool = False, + ca_certificate: Optional[str] = None, + client_certificate: Optional[str] = None, + client_key: Optional[str] = None, + ssl_credentials: Optional[grpc.ChannelCredentials] = None, + ) -> None: + super().__init__() + if not username: + raise ValueError("username cannot be empty") + if not password: + raise ValueError("password cannot be empty") + if not target: + raise ValueError("target cannot be empty") + + self.username = username + self._password: bytes = ( + password.encode("utf-8") if isinstance(password, str) else bytes(password) + ) + + # Parse target scheme + if target.startswith("http://"): + self.target = target[7:] + self.use_plain_text = True + _LOGGER.warning("Using plaintext connection for Spanner Omni credentials.") + elif target.startswith("https://"): + self.target = target[8:] + self.use_plain_text = use_plain_text + else: + self.target = target + self.use_plain_text = use_plain_text + + self.ca_certificate = ca_certificate + self.client_certificate = client_certificate + self.client_key = client_key + self.ssl_credentials = ssl_credentials + + self.token: Optional[str] = None + self.expiry: Optional[datetime.datetime] = None + self._lock = threading.Lock() + + def init_channel( + self, + use_plain_text: bool = False, + ca_certificate: Optional[str] = None, + client_certificate: Optional[str] = None, + client_key: Optional[str] = None, + ssl_credentials: Optional[grpc.ChannelCredentials] = None, + ) -> None: + """Initializes or updates channel TLS/transport settings.""" + self.use_plain_text = use_plain_text + if self.use_plain_text: + _LOGGER.warning("Using plaintext connection for Spanner Omni credentials.") + self.ca_certificate = ca_certificate + self.client_certificate = client_certificate + self.client_key = client_key + self.ssl_credentials = ssl_credentials + + def create_auth_interceptor(self, is_async: bool = False) -> Any: + """Creates a gRPC interceptor that attaches the Bearer token.""" + if is_async: + return self.create_async_auth_interceptors() + return _OmniAuthInterceptor(self) + + def create_async_auth_interceptors( + self, + ) -> Sequence[grpc.aio.ClientInterceptor]: + """Creates async gRPC interceptors that attach the Bearer token.""" + return [ + _AsyncUnaryUnaryAuthInterceptor(self), + _AsyncUnaryStreamAuthInterceptor(self), + _AsyncStreamUnaryAuthInterceptor(self), + _AsyncStreamStreamAuthInterceptor(self), + ] + + def create_async_auth_interceptor( + self, + ) -> Sequence[grpc.aio.ClientInterceptor]: + """Creates async gRPC interceptors that attach the Bearer token.""" + return self.create_async_auth_interceptors() + + def _perform_refresh_token(self, request: Any = None) -> None: + """Refreshes the access token by performing the OPAQUE login flow with Spanner Omni. + + Args: + request (Any, optional): Unused; part of google.auth.credentials.Credentials interface. + """ + with self._lock: + if self.valid: + return + login_channel = None + try: + if self.use_plain_text: + login_channel = grpc.insecure_channel(self.target) + elif self.ssl_credentials is not None: + login_channel = grpc.secure_channel( + self.target, self.ssl_credentials + ) + elif self.ca_certificate: + with open(self.ca_certificate, "rb") as f: + ca_cert = f.read() + if self.client_certificate and self.client_key: + with open(self.client_certificate, "rb") as f: + client_cert = f.read() + with open(self.client_key, "rb") as f: + private_key = f.read() + ssl_creds = grpc.ssl_channel_credentials( + root_certificates=ca_cert, + private_key=private_key, + certificate_chain=client_cert, + ) + elif self.client_certificate or self.client_key: + raise ValueError( + "Both client_certificate and client_key must be provided for mTLS" + ) + else: + ssl_creds = grpc.ssl_channel_credentials( + root_certificates=ca_cert + ) + login_channel = grpc.secure_channel(self.target, ssl_creds) + else: + raise ValueError( + "TLS/mTLS connection requires ca_certificate to be set for Spanner Omni" + ) + + client = LoginClient(login_channel) + proto_token = client.login(self.username, self._password) + + token_bytes = proto_token.SerializeToString() + self.token = base64.b64encode(token_bytes).decode("ascii") + + if proto_token.HasField("expiration_time") and ( + proto_token.expiration_time.seconds > 0 + or proto_token.expiration_time.nanos > 0 + ): + seconds = proto_token.expiration_time.seconds + nanos = proto_token.expiration_time.nanos + self.expiry = datetime.datetime.fromtimestamp( + seconds + nanos / 1e9, tz=datetime.timezone.utc + ).replace(tzinfo=None) + else: + self.expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + except (grpc.RpcError, google.auth.exceptions.RefreshError): + raise + except Exception as e: + raise google.auth.exceptions.RefreshError( + f"Failed to login to Spanner Omni: {e}" + ) from e + finally: + if login_channel is not None: + login_channel.close() + + def refresh(self, request: Any = None) -> None: + """Refreshes the access token. + + Args: + request (Any, optional): Unused; part of google.auth.credentials.Credentials interface. + """ + self._perform_refresh_token(request) + + def apply( + self, headers: MutableMapping[str, str], token: Optional[str] = None + ) -> None: + """Applies the access token to request headers.""" + headers["authorization"] = f"Bearer {token or self.token}" + + def before_request( + self, + request: Any, + method: str, + url: str, + headers: MutableMapping[str, str], + ) -> None: + """Performs token refresh if expired/missing and applies authorization header.""" + if not self.valid: + self.refresh(request) + self.apply(headers) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/login_client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/login_client.py new file mode 100644 index 000000000000..398e0d877e25 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/login_client.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Client for Spanner Omni LoginService gRPC API.""" + +from __future__ import annotations + +import queue +from typing import Iterator, Optional + +import grpc + +from google.cloud.spanner_v1.omni.opaque import ( + EXPECTED_ENVELOPE_SIZE, + UserAuthenticator, +) +from google.cloud.spanner_v1.omni.proto import ( + authentication_pb2, + login_pb2, + login_pb2_grpc, +) + + +class _RequestIterator(Iterator[login_pb2.LoginRequest]): + """Thread-safe request iterator for gRPC bidirectional streaming.""" + + def __init__(self) -> None: + self._queue: queue.Queue[Optional[login_pb2.LoginRequest]] = queue.Queue() + self._closed = False + + def send(self, request: login_pb2.LoginRequest) -> None: + self._queue.put(request) + + def close(self) -> None: + if not self._closed: + self._closed = True + self._queue.put(None) + + def __iter__(self) -> _RequestIterator: + return self + + def __next__(self) -> login_pb2.LoginRequest: + item = self._queue.get() + if item is None: + raise StopIteration + return item + + +class LoginClient: + """Client for Spanner Omni LoginService.""" + + EXPECTED_ENVELOPE_SIZE = EXPECTED_ENVELOPE_SIZE + + def __init__(self, channel: grpc.Channel) -> None: + self._stub = login_pb2_grpc.LoginServiceStub(channel) + + def login( + self, username: str, password: str | bytes, timeout: float = 60.0 + ) -> login_pb2.AccessToken: + """Performs the full OPAQUE authentication handshake and returns an AccessToken. + + Args: + username (str): The username for login. + password (str | bytes): The password for login. + timeout (float): RPC timeout in seconds. + + Returns: + login_pb2.AccessToken: The issued access token proto. + + Raises: + ValueError: If handshake validation fails. + grpc.RpcError: If gRPC communication fails. + """ + if not username: + raise ValueError("username cannot be empty") + if not password: + raise ValueError("password cannot be empty") + + req_iterator = _RequestIterator() + try: + call = self._stub.Login(req_iterator, timeout=timeout) + + def _safe_next(stage: str) -> login_pb2.LoginResponse: + try: + return next(call) + except StopIteration: + raise ValueError(f"Server closed stream prematurely during {stage}") + + # Step 1: Handshake Request + handshake_req = login_pb2.LoginRequest( + username=username, + handshake_request=authentication_pb2.PasswordAuthenticationHandshakeRequest(), + ) + req_iterator.send(handshake_req) + handshake_resp = _safe_next("handshake") + + if not handshake_resp.HasField("handshake_response"): + raise ValueError("Failed to receive handshake response from server") + + method = handshake_resp.handshake_response.password_authentication_protocol + if ( + method + != authentication_pb2.PasswordAuthenticationProtocol.PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE + ): + raise ValueError( + f"Unsupported password authentication protocol: {method}" + ) + + if not handshake_resp.handshake_response.HasField("hash_parameters"): + raise ValueError("Handshake response missing hash_parameters") + + hash_params = handshake_resp.handshake_response.hash_parameters + authenticator = UserAuthenticator(username, password, hash_params) + + # Step 2: Initial OPAQUE Request + initial_req = authenticator.initial_request() + req_iterator.send(initial_req) + initial_resp = _safe_next("initial OPAQUE exchange") + + # Step 3: Final OPAQUE Request + final_req = authenticator.final_request(initial_resp) + req_iterator.send(final_req) + req_iterator.close() + + # Final Response with AccessToken + final_resp = _safe_next("final OPAQUE exchange") + if not final_resp.HasField("access_token"): + raise ValueError( + "Server failed to return an access token in final response" + ) + + return final_resp.access_token + except Exception: + if "call" in locals() and hasattr(call, "cancel"): + call.cancel() + req_iterator.close() + raise diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/opaque.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/opaque.py new file mode 100644 index 000000000000..e9974e2137e1 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/opaque.py @@ -0,0 +1,604 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""OPAQUE protocol cryptographic utilities for Spanner Omni authentication.""" + +from __future__ import annotations + +import hashlib +import hmac +import secrets +from typing import Optional, Tuple + +try: + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.kdf.argon2 import Argon2id + from cryptography.hazmat.primitives.kdf.hkdf import HKDF +except ImportError as err: + raise ImportError( + "The 'cryptography' package is required for Spanner Omni authentication. " + "Please install it with 'pip install google-cloud-spanner[omni]'." + ) from err + +from google.cloud.spanner_v1.omni.proto import login_pb2 + +LOGIN_DOMAIN_SEPARATION_TAG = b"Spanner-Omni-Login" +AUTH_KEY_INFO = b"AuthKey" +EXPORT_KEY_INFO = b"ExportKey" +PRIVATE_KEY_INFO = b"PrivateKey" +MASKING_KEY_INFO = b"MaskingKey" +DIFFIE_HELLMAN_KEY_INFO = b"OPAQUE-DeriveDiffieHellmanKeyPair" + +NONCE_LENGTH = 32 +MAC_TAG_LENGTH = 32 +PUBLIC_KEY_LENGTH = 33 +EXPECTED_ENVELOPE_SIZE = PUBLIC_KEY_LENGTH + NONCE_LENGTH + MAC_TAG_LENGTH # 97 + +# NIST P-256 (secp256r1) Curve Constants +P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF +A = (P - 3) % P +B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B +Z = (P - 10) % P +ORDER = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 +GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296 +GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5 +G = (GX, GY) +P_MINUS_1_OVER_2 = (P - 1) // 2 +P_PLUS_1_OVER_4 = (P + 1) // 4 + + +def _clear(b: Optional[bytearray]) -> None: + """Zeroizes a mutable bytearray in place.""" + if b is not None: + for i in range(len(b)): + b[i] = 0 + + +def point_add( + p1: Optional[Tuple[int, int]], p2: Optional[Tuple[int, int]] +) -> Optional[Tuple[int, int]]: + """Adds two points on the P-256 elliptic curve.""" + if p1 is None: + return p2 + if p2 is None: + return p1 + x1, y1 = p1 + x2, y2 = p2 + if x1 == x2: + if (y1 + y2) % P == 0: + return None + lam = ((3 * x1 * x1 + A) * pow(2 * y1, P - 2, P)) % P + else: + lam = ((y2 - y1) * pow(x2 - x1, P - 2, P)) % P + x3 = (lam * lam - x1 - x2) % P + y3 = (lam * (x1 - x3) - y1) % P + return (x3, y3) + + +def point_mul(pt: Optional[Tuple[int, int]], k: int) -> Optional[Tuple[int, int]]: + """Multiplies a point on the P-256 elliptic curve by a scalar k.""" + if pt is None or k == 0: + return None + res = None + curr = pt + while k > 0: + if k & 1: + res = point_add(res, curr) + curr = point_add(curr, curr) + k >>= 1 + return res + + +def marshal_compressed(pt: Optional[Tuple[int, int]]) -> bytes: + """Encodes a P-256 curve point into 33-byte compressed SEC1 format.""" + if pt is None: + raise ValueError("Point at infinity cannot be compressed") + x, y = pt + prefix = b"\x02" if (y % 2 == 0) else b"\x03" + return prefix + x.to_bytes(32, "big") + + +def unmarshal_compressed(data: bytes) -> Tuple[int, int]: + """Decodes a 33-byte compressed SEC1 format point on P-256.""" + if len(data) != 33: + raise ValueError(f"Invalid compressed point length: {len(data)}") + prefix = data[0] + if prefix not in (2, 3): + raise ValueError(f"Invalid compressed point prefix: {prefix}") + x = int.from_bytes(data[1:], "big") + if x >= P: + raise ValueError("x coordinate exceeds field prime") + rhs = (pow(x, 3, P) + A * x + B) % P + y = pow(rhs, P_PLUS_1_OVER_4, P) + if (pow(y, 2, P) - rhs) % P != 0: + raise ValueError("Point is not on curve") + if (y % 2) != (prefix & 1): + y = (P - y) % P + return (x, y) + + +def expand_message_xmd(msg: bytes, dst: bytes, len_in_bytes: int) -> bytes: + """Implements expand_message_xmd for SHA-256 per RFC 9380 Section 5.3.1.""" + if len(dst) > 255: + dst = hashlib.sha256(b"H2C-OVERSIZE-DST-" + dst).digest() + dst_len = bytes([len(dst)]) + b_in_bytes = 32 + ell = (len_in_bytes + b_in_bytes - 1) // b_in_bytes + z_pad = b"\x00" * 64 + lib_str = len_in_bytes.to_bytes(2, "big") + h = hashlib.sha256() + h.update(z_pad) + h.update(msg) + h.update(lib_str) + h.update(b"\x00") + h.update(dst) + h.update(dst_len) + b0 = h.digest() + b1 = hashlib.sha256(b0 + b"\x01" + dst + dst_len).digest() + res = bytearray(b1) + prev = b1 + for i in range(2, ell + 1): + tmp = bytes(x ^ y for x, y in zip(b0, prev)) + bi = hashlib.sha256(tmp + bytes([i]) + dst + dst_len).digest() + res.extend(bi) + prev = bi + return bytes(res[:len_in_bytes]) + + +def map_to_curve_sswu(u: int) -> Tuple[int, int]: + """Implements Simplified SWU mapping for P-256 per RFC 9380 Section 6.6.2.""" + u2 = (u * u) % P + tv1 = (Z * u2) % P + tv2 = (tv1 * tv1 + tv1) % P + tv3 = (B * (tv2 + 1)) % P + + if tv2 != 0: + tv4 = (-tv2) % P + else: + tv4 = Z + tv4 = (tv4 * A) % P + + tv4_inv = pow(tv4, P - 2, P) + x1 = (tv3 * tv4_inv) % P + + gx1 = (pow(x1, 3, P) + A * x1 + B) % P + e1 = pow(gx1, P_MINUS_1_OVER_2, P) + is_square = e1 == 1 or gx1 == 0 + + if is_square: + x = x1 + y = pow(gx1, P_PLUS_1_OVER_4, P) + else: + x = (tv1 * x1) % P + gx2 = (pow(x, 3, P) + A * x + B) % P + y = pow(gx2, P_PLUS_1_OVER_4, P) + + if (u & 1) != (y & 1): + y = (P - y) % P + return (x, y) + + +def hash_to_curve_p256(msg: bytes, dst: bytes) -> Tuple[int, int]: + """Implements P256_XMD:SHA-256_SSWU_RO_ hash-to-curve per RFC 9380 Section 8.2.""" + ub = expand_message_xmd(msg, dst, 96) + u0 = int.from_bytes(ub[:48], "big") % P + u1 = int.from_bytes(ub[48:], "big") % P + q0 = map_to_curve_sswu(u0) + q1 = map_to_curve_sswu(u1) + res = point_add(q0, q1) + if res is None: + raise ValueError("Hash to curve produced point at infinity") + return res + + +def nonce() -> bytes: + """Generates a 32-byte cryptographically secure random nonce.""" + return secrets.token_bytes(NONCE_LENGTH) + + +def sha256_hash(data: bytes) -> bytes: + """Computes the SHA-256 digest of input data.""" + return hashlib.sha256(data).digest() + + +def hmac_sha256(key: bytes, message: bytes) -> bytes: + """Computes HMAC-SHA-256.""" + return hmac.new(key, message, hashlib.sha256).digest() + + +def mac(key: bytes, data: bytes) -> bytes: + """Computes a 32-byte MAC tag using HMAC-SHA-256.""" + return hmac_sha256(key, data)[:MAC_TAG_LENGTH] + + +def xor_bytes(a: bytes, b: bytes) -> bytes: + """Computes bitwise XOR of two equal-length byte sequences.""" + if len(a) != len(b): + raise ValueError(f"Byte sequences must have equal length: {len(a)} != {len(b)}") + return (int.from_bytes(a, "big") ^ int.from_bytes(b, "big")).to_bytes(len(a), "big") + + +def concat(*arrays: bytes) -> bytes: + """Concatenates multiple byte sequences.""" + return b"".join(arrays) + + +def expand(input_key_material: bytes, info: bytes, size: int) -> bytes: + """Expands key material using HKDF with SHA-256.""" + hkdf = HKDF( + algorithm=hashes.SHA256(), + length=size, + salt=b"", + info=info, + ) + return hkdf.derive(input_key_material) + + +def extract(input_key_material: bytes) -> bytes: + """Extracts key material using HKDF with label 'Extract'.""" + return expand(input_key_material, b"Extract", 32) + + +def _validate_hash_parameters(hash_parameters) -> None: + if hash_parameters is None: + raise ValueError("hash_parameters cannot be None") + if hasattr(hash_parameters, "HasField"): + if not hash_parameters.HasField("argon2_id_parameters"): + raise ValueError( + "hash_parameters must contain non-nil argon2_id_parameters" + ) + argon2_params = hash_parameters.argon2_id_parameters + else: + argon2_params = getattr(hash_parameters, "argon2_id_parameters", None) + if argon2_params is None: + raise ValueError( + "hash_parameters must contain non-nil argon2_id_parameters" + ) + + if not (1 <= argon2_params.iteration_count <= 10): + raise ValueError( + f"Invalid Argon2Id iteration count: {argon2_params.iteration_count} (must be between 1 and 10)" + ) + if not (8 <= argon2_params.memory_usage <= 65536): + raise ValueError( + f"Invalid Argon2Id memory usage: {argon2_params.memory_usage} (must be between 8 and 65536 KB)" + ) + if not (1 <= argon2_params.parallelism <= 255): + raise ValueError( + f"Invalid Argon2Id parallelism: {argon2_params.parallelism} (must be between 1 and 255)" + ) + if not (8 <= argon2_params.hash_size <= 512): + raise ValueError( + f"Invalid Argon2Id hash size: {argon2_params.hash_size} (must be between 8 and 512)" + ) + + +def stretch(input_bytes: bytes, hash_parameters) -> bytes: + """Stretches the OPRF evaluation using Argon2id with server hash parameters.""" + _validate_hash_parameters(hash_parameters) + argon2_params = hash_parameters.argon2_id_parameters + + salt = expand(input_bytes, b"Stretch", int(argon2_params.hash_size)) + argon2 = Argon2id( + salt=salt, + length=int(argon2_params.hash_size), + iterations=int(argon2_params.iteration_count), + lanes=int(argon2_params.parallelism), + memory_cost=int(argon2_params.memory_usage), + ) + return argon2.derive(input_bytes) + + +def random_oracle_sha256(x: bytes, max_val: int) -> bytes: + """Iterative SHA-256 random oracle reduction mod max_val.""" + hash_output_length = 256 + output_bit_length = max_val.bit_length() + hash_output_length + iter_count = (output_bit_length + hash_output_length - 1) // hash_output_length + if iter_count > 255: + raise ValueError( + f"Domain bit length must not be greater than 65280: {output_bit_length}" + ) + excess_bit_count = (iter_count * hash_output_length) - output_bit_length + hash_output = 0 + for i in range(1, iter_count + 1): + hash_output <<= hash_output_length + bignum_bytes = bytes([i]) + x + hashed_string = hashlib.sha256(bignum_bytes).digest() + new_big_num = int.from_bytes(hashed_string, "big") + hash_output += new_big_num + + hash_output >>= excess_bit_count + hash_output %= max_val + + scalar_len = hash_output_length // 8 + max_len = (max_val.bit_length() + 7) // 8 + if max_len > scalar_len: + scalar_len = max_len + return hash_output.to_bytes(scalar_len, "big") + + +def derive_key_pair(seed: bytes, info: bytes) -> Tuple[bytes, bytes]: + """Derives an ECDH public/private keypair from a seed and info string.""" + derive_input = seed + info + priv_bytes = random_oracle_sha256(derive_input, ORDER) + priv_int = int.from_bytes(priv_bytes, "big") + if priv_int == 0: + priv_int = 1 + priv_bytes = (1).to_bytes(32, "big") + pub_point = point_mul(G, priv_int) + pub_bytes = marshal_compressed(pub_point) + return pub_bytes, priv_bytes + + +def diffie_hellman(priv_bytes: bytes, pub_bytes: bytes) -> bytes: + """Computes the ECDH shared point peer_pub * priv.""" + pt = unmarshal_compressed(pub_bytes) + priv_int = int.from_bytes(priv_bytes, "big") + shared_pt = point_mul(pt, priv_int) + return marshal_compressed(shared_pt) + + +def blind(password: bytes, blind_scalar: Optional[bytes] = None) -> Tuple[bytes, bytes]: + """Blinds the password point using a random or provided scalar.""" + if len(password) == 0: + raise ValueError("Password cannot be empty") + pt = hash_to_curve_p256(password, LOGIN_DOMAIN_SEPARATION_TAG) + if blind_scalar is None: + while True: + r = secrets.randbelow(ORDER) + if r != 0: + break + blind_scalar = r.to_bytes(32, "big") + else: + r = int.from_bytes(blind_scalar, "big") + blinded_pt = point_mul(pt, r) + return marshal_compressed(blinded_pt), blind_scalar + + +def finalize(blind_scalar: bytes, evaluated_message: bytes) -> bytes: + """Finalizes the OPRF output by multiplying with r^-1 mod Order.""" + if len(blind_scalar) == 0: + raise ValueError("Blind scalar cannot be empty") + r = int.from_bytes(blind_scalar, "big") + r_inv = pow(r, ORDER - 2, ORDER) + eval_pt = unmarshal_compressed(evaluated_message) + res_pt = point_mul(eval_pt, r_inv) + return marshal_compressed(res_pt) + + +def derive_secret( + input_key_material: bytes, label: bytes, transcript_hash: bytes +) -> bytes: + """Derives a secret labeled with 'OPAQUE-'.""" + info = b"OPAQUE-" + label + transcript_hash + return expand(input_key_material, info, 32) + + +def derive_shared_keys( + input_key_material: bytes, preamble: bytes +) -> Tuple[bytes, bytes, bytes]: + """Derives the km2 (server MAC), km3 (client MAC), and sessionKey.""" + prk = extract(input_key_material) + preamble_hash = sha256_hash(preamble) + handshake_secret = derive_secret(prk, b"HandshakeSecret", preamble_hash) + session_key = derive_secret(prk, b"SessionKey", preamble_hash) + km2 = derive_secret(handshake_secret, b"ServerMAC", b"") + km3 = derive_secret(handshake_secret, b"ClientMAC", b"") + return km2, km3, session_key + + +def recover_client( + username: str, + randomized_password: bytes, + envelope_nonce: bytes, + auth_tag: bytes, + server_public_key: bytes, +) -> Tuple[bytes, bytes]: + """Recovers the client's export key and private key from the envelope.""" + auth_key = expand(randomized_password, envelope_nonce + AUTH_KEY_INFO, 32) + export_key = expand(randomized_password, envelope_nonce + EXPORT_KEY_INFO, 32) + seed = expand(randomized_password, envelope_nonce + PRIVATE_KEY_INFO, 32) + _, client_private_key = derive_key_pair(seed, DIFFIE_HELLMAN_KEY_INFO) + + expected_tag = mac( + auth_key, envelope_nonce + server_public_key + username.encode("utf-8") + ) + if len(auth_tag) != len(expected_tag) or not hmac.compare_digest( + expected_tag, auth_tag + ): + raise ValueError("Auth tag mismatch") + return export_key, client_private_key + + +class UserAuthenticator: + """Manages the client state and key exchanges for OPAQUE login authentication.""" + + def clear(self) -> None: + """Zeroizes and clears all sensitive cryptographic state.""" + _clear(self._password) + self._password = None + _clear(self._blind) + self._blind = None + _clear(self._client_private_keyshare) + self._client_private_keyshare = None + + def __del__(self) -> None: + self.clear() + + def __init__(self, username: str, password: str | bytes, hash_parameters): + self.username = None + self._password: Optional[bytearray] = None + self.hash_parameters = None + self._blind: Optional[bytearray] = None + self._client_nonce: Optional[bytes] = None + self._client_public_keyshare: Optional[bytes] = None + self._client_private_keyshare: Optional[bytearray] = None + + if not username: + raise ValueError("username cannot be empty") + if isinstance(password, str): + password = password.encode("utf-8") + if len(password) == 0: + raise ValueError("password cannot be empty") + if hash_parameters is None: + raise ValueError("hash_parameters cannot be None") + _validate_hash_parameters(hash_parameters) + + self.username = username + self._password = bytearray(password) + self.hash_parameters = hash_parameters + + def initial_request(self) -> login_pb2.LoginRequest: + """Generates the initial OPAQUE login request.""" + if self._password is None: + raise ValueError("Authenticator already used or password not available") + + try: + blinded_message, blind_scalar = blind(self._password) + self._blind = bytearray(blind_scalar) + + self._client_nonce = nonce() + random_nonce = nonce() + + pub_key, priv_key = derive_key_pair(random_nonce, DIFFIE_HELLMAN_KEY_INFO) + self._client_public_keyshare = pub_key + self._client_private_keyshare = bytearray(priv_key) + + initial_opaque_req = login_pb2.InitialOpaqueLoginRequest( + blinded_message=blinded_message, + client_nonce=self._client_nonce, + client_public_keyshare=self._client_public_keyshare, + ) + opaque_req = login_pb2.OpaqueLoginRequest( + initial_request=initial_opaque_req + ) + return login_pb2.LoginRequest( + username=self.username, + opaque_request=opaque_req, + ) + finally: + _clear(self._password) + self._password = None + + def final_request( + self, initial_response: login_pb2.LoginResponse + ) -> login_pb2.LoginRequest: + """Generates the final OPAQUE login request containing the client MAC.""" + if initial_response is None: + raise ValueError("initial_response cannot be None") + if ( + self._client_public_keyshare is None + or self._client_nonce is None + or self._client_private_keyshare is None + or self._blind is None + ): + raise ValueError( + "Authenticator not initialized; initial_request must be called first" + ) + + if ( + not hasattr(initial_response, "HasField") + or not initial_response.HasField("opaque_response") + or not initial_response.opaque_response.HasField("initial_response") + ): + raise ValueError("Expected initial opaque response from server") + + initial_opaque_resp = initial_response.opaque_response.initial_response + + evaluated_message = initial_opaque_resp.evaluated_message + masking_nonce = initial_opaque_resp.masking_nonce + masked_response = initial_opaque_resp.masked_response + server_nonce = initial_opaque_resp.server_nonce + server_mac = initial_opaque_resp.server_mac + server_public_keyshare = initial_opaque_resp.server_public_keyshare + + if len(masked_response) != EXPECTED_ENVELOPE_SIZE: + raise ValueError( + f"Invalid masked response length: got {len(masked_response)}, want {EXPECTED_ENVELOPE_SIZE}" + ) + + try: + oprf = finalize(self._blind, evaluated_message) + stretched_oprf = stretch(oprf, self.hash_parameters) + randomized_password = extract(concat(oprf, stretched_oprf)) + + masking_key = expand(randomized_password, MASKING_KEY_INFO, 32) + credential_response_pad = expand( + masking_key, + concat(masking_nonce, b"CredentialResponsePad"), + len(masked_response), + ) + serialized_envelope = xor_bytes(masked_response, credential_response_pad) + if len(serialized_envelope) != EXPECTED_ENVELOPE_SIZE: + raise ValueError( + f"Invalid serialized envelope length: got {len(serialized_envelope)}, want {EXPECTED_ENVELOPE_SIZE}" + ) + + server_public_key = serialized_envelope[:PUBLIC_KEY_LENGTH] + envelope_nonce = serialized_envelope[ + PUBLIC_KEY_LENGTH : PUBLIC_KEY_LENGTH + NONCE_LENGTH + ] + auth_tag = serialized_envelope[ + PUBLIC_KEY_LENGTH + NONCE_LENGTH : EXPECTED_ENVELOPE_SIZE + ] + + export_key, client_private_key = recover_client( + self.username, + randomized_password, + envelope_nonce, + auth_tag, + server_public_key, + ) + + dh1 = diffie_hellman(self._client_private_keyshare, server_public_keyshare) + dh2 = diffie_hellman(self._client_private_keyshare, server_public_key) + dh3 = diffie_hellman(client_private_key, server_public_keyshare) + + input_key_material = concat(dh1, dh2, dh3) + + preamble = concat( + b"OPAQUEv1-", + self.username.encode("utf-8"), + self._client_nonce, + self._client_public_keyshare, + server_public_key, + evaluated_message, + server_nonce, + server_public_keyshare, + ) + + km2, km3, _ = derive_shared_keys(input_key_material, preamble) + + hashed_preamble = sha256_hash(preamble) + expected_server_mac = mac(km2, hashed_preamble) + if len(server_mac) != len(expected_server_mac) or not hmac.compare_digest( + expected_server_mac, server_mac + ): + raise ValueError("Server MAC mismatch") + + client_mac = mac(km3, sha256_hash(concat(preamble, expected_server_mac))) + + final_opaque_req = login_pb2.FinalOpaqueLoginRequest(client_mac=client_mac) + opaque_req = login_pb2.OpaqueLoginRequest(final_request=final_opaque_req) + return login_pb2.LoginRequest( + username=self.username, + opaque_request=opaque_req, + ) + finally: + _clear(self._blind) + self._blind = None + _clear(self._client_private_keyshare) + self._client_private_keyshare = None diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/__init__.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/__init__.py new file mode 100644 index 000000000000..b433d320f3b3 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/__init__.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.spanner_v1.omni.proto import ( + authentication_pb2, + login_pb2, + login_pb2_grpc, +) + +__all__ = ( + "authentication_pb2", + "login_pb2", + "login_pb2_grpc", +) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2.py new file mode 100644 index 000000000000..1b0c45c8939d --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/cloud/spanner_v1/omni/proto/authentication.proto +# Protobuf Python Version: 7.35.1 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 5, + "", + "google/cloud/spanner_v1/omni/proto/authentication.proto", +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n7google/cloud/spanner_v1/omni/proto/authentication.proto\x12\x16google.spanner.auth.v1"\xe6\x01\n\x0eHashParameters\x12Y\n\x14\x61rgon2_id_parameters\x18\x01 \x01(\x0b\x32\x39.google.spanner.auth.v1.HashParameters.Argon2IdParametersH\x00\x1ak\n\x12\x41rgon2IdParameters\x12\x17\n\x0fiteration_count\x18\x01 \x01(\r\x12\x14\n\x0cmemory_usage\x18\x02 \x01(\r\x12\x13\n\x0bparallelism\x18\x03 \x01(\r\x12\x11\n\thash_size\x18\x04 \x01(\rB\x0c\n\nparameters"(\n&PasswordAuthenticationHandshakeRequest"\xcc\x01\n\'PasswordAuthenticationHandshakeResponse\x12`\n password_authentication_protocol\x18\x01 \x01(\x0e\x32\x36.google.spanner.auth.v1.PasswordAuthenticationProtocol\x12?\n\x0fhash_parameters\x18\x02 \x01(\x0b\x32&.google.spanner.auth.v1.HashParameters*\x7f\n\x1ePasswordAuthenticationProtocol\x12\x30\n,PASSWORD_AUTHENTICATION_PROTOCOL_UNSPECIFIED\x10\x00\x12+\n\'PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE\x10\x02\x42\x43\n\x1d\x63om.google.cloud.spanner.omniP\x01Z cloud.google.com/go/spanner/omnib\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.cloud.spanner_v1.omni.proto.authentication_pb2", _globals +) +if not _descriptor._USE_C_DESCRIPTORS: + _globals["DESCRIPTOR"]._loaded_options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = ( + b"\n\035com.google.cloud.spanner.omniP\001Z cloud.google.com/go/spanner/omni" + ) + _globals["_PASSWORDAUTHENTICATIONPROTOCOL"]._serialized_start = 565 + _globals["_PASSWORDAUTHENTICATIONPROTOCOL"]._serialized_end = 692 + _globals["_HASHPARAMETERS"]._serialized_start = 84 + _globals["_HASHPARAMETERS"]._serialized_end = 314 + _globals["_HASHPARAMETERS_ARGON2IDPARAMETERS"]._serialized_start = 193 + _globals["_HASHPARAMETERS_ARGON2IDPARAMETERS"]._serialized_end = 300 + _globals["_PASSWORDAUTHENTICATIONHANDSHAKEREQUEST"]._serialized_start = 316 + _globals["_PASSWORDAUTHENTICATIONHANDSHAKEREQUEST"]._serialized_end = 356 + _globals["_PASSWORDAUTHENTICATIONHANDSHAKERESPONSE"]._serialized_start = 359 + _globals["_PASSWORDAUTHENTICATIONHANDSHAKERESPONSE"]._serialized_end = 563 +# @@protoc_insertion_point(module_scope) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2.pyi b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2.pyi new file mode 100644 index 000000000000..caa2fb9a2332 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2.pyi @@ -0,0 +1,81 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Mapping as _Mapping +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class PasswordAuthenticationProtocol(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + PASSWORD_AUTHENTICATION_PROTOCOL_UNSPECIFIED: _ClassVar[ + PasswordAuthenticationProtocol + ] + PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE: _ClassVar[PasswordAuthenticationProtocol] + +PASSWORD_AUTHENTICATION_PROTOCOL_UNSPECIFIED: PasswordAuthenticationProtocol +PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE: PasswordAuthenticationProtocol + +class HashParameters(_message.Message): + __slots__ = ("argon2_id_parameters",) + class Argon2IdParameters(_message.Message): + __slots__ = ("iteration_count", "memory_usage", "parallelism", "hash_size") + ITERATION_COUNT_FIELD_NUMBER: _ClassVar[int] + MEMORY_USAGE_FIELD_NUMBER: _ClassVar[int] + PARALLELISM_FIELD_NUMBER: _ClassVar[int] + HASH_SIZE_FIELD_NUMBER: _ClassVar[int] + iteration_count: int + memory_usage: int + parallelism: int + hash_size: int + def __init__( + self, + iteration_count: _Optional[int] = ..., + memory_usage: _Optional[int] = ..., + parallelism: _Optional[int] = ..., + hash_size: _Optional[int] = ..., + ) -> None: ... + + ARGON2_ID_PARAMETERS_FIELD_NUMBER: _ClassVar[int] + argon2_id_parameters: HashParameters.Argon2IdParameters + def __init__( + self, + argon2_id_parameters: _Optional[ + _Union[HashParameters.Argon2IdParameters, _Mapping] + ] = ..., + ) -> None: ... + +class PasswordAuthenticationHandshakeRequest(_message.Message): + __slots__ = () + def __init__(self) -> None: ... + +class PasswordAuthenticationHandshakeResponse(_message.Message): + __slots__ = ("password_authentication_protocol", "hash_parameters") + PASSWORD_AUTHENTICATION_PROTOCOL_FIELD_NUMBER: _ClassVar[int] + HASH_PARAMETERS_FIELD_NUMBER: _ClassVar[int] + password_authentication_protocol: PasswordAuthenticationProtocol + hash_parameters: HashParameters + def __init__( + self, + password_authentication_protocol: _Optional[ + _Union[PasswordAuthenticationProtocol, str] + ] = ..., + hash_parameters: _Optional[_Union[HashParameters, _Mapping]] = ..., + ) -> None: ... diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2_grpc.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2_grpc.py new file mode 100644 index 000000000000..ef4c49f28e09 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/authentication_pb2_grpc.py @@ -0,0 +1,26 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" + +import grpc + +GRPC_GENERATED_VERSION = "1.59.0" +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + + _version_not_supported = first_version_is_lower( + GRPC_VERSION, GRPC_GENERATED_VERSION + ) +except ImportError: + _version_not_supported = False + +if _version_not_supported: + raise RuntimeError( + f"The grpc package installed is at version {GRPC_VERSION}," + + " but the generated code in google/cloud/spanner_v1/omni/proto/authentication_pb2_grpc.py depends on" + + f" grpcio>={GRPC_GENERATED_VERSION}." + + f" Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}" + + f" or downgrade your generated code using grpcio-tools<={GRPC_VERSION}." + ) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2.py new file mode 100644 index 000000000000..3e0e7e24fcbd --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/cloud/spanner_v1/omni/proto/login.proto +# Protobuf Python Version: 7.35.1 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 5, + "", + "google/cloud/spanner_v1/omni/proto/login.proto", +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + +from google.cloud.spanner_v1.omni.proto import ( + authentication_pb2 as google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_authentication__pb2, +) + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n.google/cloud/spanner_v1/omni/proto/login.proto\x12\x16google.spanner.auth.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x37google/cloud/spanner_v1/omni/proto/authentication.proto"\xe5\x02\n\x0b\x41\x63\x63\x65ssToken\x12\x10\n\x08username\x18\x01 \x01(\t\x12\x31\n\rcreation_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x0f\x65xpiration_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x11\n\tsignature\x18\x04 \x01(\x0c\x12\x0e\n\x06key_id\x18\x05 \x01(\x03\x12N\n\x11\x61\x63\x63\x65ss_token_type\x18\x06 \x01(\x0e\x32\x33.google.spanner.auth.v1.AccessToken.AccessTokenType"i\n\x0f\x41\x63\x63\x65ssTokenType\x12!\n\x1d\x41\x43\x43\x45SS_TOKEN_TYPE_UNSPECIFIED\x10\x00\x12\x19\n\x15\x41\x43\x43\x45SS_TOKEN_TYPE_API\x10\x01\x12\x18\n\x14\x41\x43\x43\x45SS_TOKEN_TYPE_UI\x10\x02"j\n\x19InitialOpaqueLoginRequest\x12\x17\n\x0f\x62linded_message\x18\x01 \x01(\x0c\x12\x14\n\x0c\x63lient_nonce\x18\x02 \x01(\x0c\x12\x1e\n\x16\x63lient_public_keyshare\x18\x03 \x01(\x0c"-\n\x17\x46inalOpaqueLoginRequest\x12\x12\n\nclient_mac\x18\x01 \x01(\x0c"\xb1\x01\n\x1aInitialOpaqueLoginResponse\x12\x14\n\x0cserver_nonce\x18\x01 \x01(\x0c\x12\x1e\n\x16server_public_keyshare\x18\x02 \x01(\x0c\x12\x12\n\nserver_mac\x18\x03 \x01(\x0c\x12\x19\n\x11\x65valuated_message\x18\x04 \x01(\x0c\x12\x15\n\rmasking_nonce\x18\x05 \x01(\x0c\x12\x17\n\x0fmasked_response\x18\x06 \x01(\x0c"\xb7\x01\n\x12OpaqueLoginRequest\x12L\n\x0finitial_request\x18\x01 \x01(\x0b\x32\x31.google.spanner.auth.v1.InitialOpaqueLoginRequestH\x00\x12H\n\rfinal_request\x18\x02 \x01(\x0b\x32/.google.spanner.auth.v1.FinalOpaqueLoginRequestH\x00\x42\t\n\x07request"\xd7\x01\n\x13OpaqueLoginResponse\x12N\n\x10initial_response\x18\x01 \x01(\x0b\x32\x32.google.spanner.auth.v1.InitialOpaqueLoginResponseH\x00\x12S\n\x0e\x66inal_response\x18\x02 \x01(\x0b\x32\x39.google.spanner.auth.v1.OpaqueLoginResponse.FinalResponseH\x00\x1a\x0f\n\rFinalResponseB\n\n\x08response"\xce\x01\n\x0cLoginRequest\x12\x10\n\x08username\x18\x01 \x01(\t\x12\x44\n\x0eopaque_request\x18\x04 \x01(\x0b\x32*.google.spanner.auth.v1.OpaqueLoginRequestH\x00\x12[\n\x11handshake_request\x18\x05 \x01(\x0b\x32>.google.spanner.auth.v1.PasswordAuthenticationHandshakeRequestH\x00\x42\t\n\x07request"\xfd\x01\n\rLoginResponse\x12\x39\n\x0c\x61\x63\x63\x65ss_token\x18\x01 \x01(\x0b\x32#.google.spanner.auth.v1.AccessToken\x12\x46\n\x0fopaque_response\x18\x04 \x01(\x0b\x32+.google.spanner.auth.v1.OpaqueLoginResponseH\x00\x12]\n\x12handshake_response\x18\x05 \x01(\x0b\x32?.google.spanner.auth.v1.PasswordAuthenticationHandshakeResponseH\x00\x42\n\n\x08response2h\n\x0cLoginService\x12X\n\x05Login\x12$.google.spanner.auth.v1.LoginRequest\x1a%.google.spanner.auth.v1.LoginResponse(\x01\x30\x01\x42\x43\n\x1d\x63om.google.cloud.spanner.omniP\x01Z cloud.google.com/go/spanner/omnib\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.cloud.spanner_v1.omni.proto.login_pb2", _globals +) +if not _descriptor._USE_C_DESCRIPTORS: + _globals["DESCRIPTOR"]._loaded_options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = ( + b"\n\035com.google.cloud.spanner.omniP\001Z cloud.google.com/go/spanner/omni" + ) + _globals["_ACCESSTOKEN"]._serialized_start = 165 + _globals["_ACCESSTOKEN"]._serialized_end = 522 + _globals["_ACCESSTOKEN_ACCESSTOKENTYPE"]._serialized_start = 417 + _globals["_ACCESSTOKEN_ACCESSTOKENTYPE"]._serialized_end = 522 + _globals["_INITIALOPAQUELOGINREQUEST"]._serialized_start = 524 + _globals["_INITIALOPAQUELOGINREQUEST"]._serialized_end = 630 + _globals["_FINALOPAQUELOGINREQUEST"]._serialized_start = 632 + _globals["_FINALOPAQUELOGINREQUEST"]._serialized_end = 677 + _globals["_INITIALOPAQUELOGINRESPONSE"]._serialized_start = 680 + _globals["_INITIALOPAQUELOGINRESPONSE"]._serialized_end = 857 + _globals["_OPAQUELOGINREQUEST"]._serialized_start = 860 + _globals["_OPAQUELOGINREQUEST"]._serialized_end = 1043 + _globals["_OPAQUELOGINRESPONSE"]._serialized_start = 1046 + _globals["_OPAQUELOGINRESPONSE"]._serialized_end = 1261 + _globals["_OPAQUELOGINRESPONSE_FINALRESPONSE"]._serialized_start = 1234 + _globals["_OPAQUELOGINRESPONSE_FINALRESPONSE"]._serialized_end = 1249 + _globals["_LOGINREQUEST"]._serialized_start = 1264 + _globals["_LOGINREQUEST"]._serialized_end = 1470 + _globals["_LOGINRESPONSE"]._serialized_start = 1473 + _globals["_LOGINRESPONSE"]._serialized_end = 1726 + _globals["_LOGINSERVICE"]._serialized_start = 1728 + _globals["_LOGINSERVICE"]._serialized_end = 1832 +# @@protoc_insertion_point(module_scope) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2.pyi b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2.pyi new file mode 100644 index 000000000000..5eda2eee3e65 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2.pyi @@ -0,0 +1,190 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +from collections.abc import Mapping as _Mapping +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import timestamp_pb2 as _timestamp_pb2 +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +from google.cloud.spanner_v1.omni.proto import authentication_pb2 as _authentication_pb2 + +DESCRIPTOR: _descriptor.FileDescriptor + +class AccessToken(_message.Message): + __slots__ = ( + "username", + "creation_time", + "expiration_time", + "signature", + "key_id", + "access_token_type", + ) + class AccessTokenType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + ACCESS_TOKEN_TYPE_UNSPECIFIED: _ClassVar[AccessToken.AccessTokenType] + ACCESS_TOKEN_TYPE_API: _ClassVar[AccessToken.AccessTokenType] + ACCESS_TOKEN_TYPE_UI: _ClassVar[AccessToken.AccessTokenType] + + ACCESS_TOKEN_TYPE_UNSPECIFIED: AccessToken.AccessTokenType + ACCESS_TOKEN_TYPE_API: AccessToken.AccessTokenType + ACCESS_TOKEN_TYPE_UI: AccessToken.AccessTokenType + USERNAME_FIELD_NUMBER: _ClassVar[int] + CREATION_TIME_FIELD_NUMBER: _ClassVar[int] + EXPIRATION_TIME_FIELD_NUMBER: _ClassVar[int] + SIGNATURE_FIELD_NUMBER: _ClassVar[int] + KEY_ID_FIELD_NUMBER: _ClassVar[int] + ACCESS_TOKEN_TYPE_FIELD_NUMBER: _ClassVar[int] + username: str + creation_time: _timestamp_pb2.Timestamp + expiration_time: _timestamp_pb2.Timestamp + signature: bytes + key_id: int + access_token_type: AccessToken.AccessTokenType + def __init__( + self, + username: _Optional[str] = ..., + creation_time: _Optional[ + _Union[datetime.datetime, _timestamp_pb2.Timestamp, _Mapping] + ] = ..., + expiration_time: _Optional[ + _Union[datetime.datetime, _timestamp_pb2.Timestamp, _Mapping] + ] = ..., + signature: _Optional[bytes] = ..., + key_id: _Optional[int] = ..., + access_token_type: _Optional[_Union[AccessToken.AccessTokenType, str]] = ..., + ) -> None: ... + +class InitialOpaqueLoginRequest(_message.Message): + __slots__ = ("blinded_message", "client_nonce", "client_public_keyshare") + BLINDED_MESSAGE_FIELD_NUMBER: _ClassVar[int] + CLIENT_NONCE_FIELD_NUMBER: _ClassVar[int] + CLIENT_PUBLIC_KEYSHARE_FIELD_NUMBER: _ClassVar[int] + blinded_message: bytes + client_nonce: bytes + client_public_keyshare: bytes + def __init__( + self, + blinded_message: _Optional[bytes] = ..., + client_nonce: _Optional[bytes] = ..., + client_public_keyshare: _Optional[bytes] = ..., + ) -> None: ... + +class FinalOpaqueLoginRequest(_message.Message): + __slots__ = ("client_mac",) + CLIENT_MAC_FIELD_NUMBER: _ClassVar[int] + client_mac: bytes + def __init__(self, client_mac: _Optional[bytes] = ...) -> None: ... + +class InitialOpaqueLoginResponse(_message.Message): + __slots__ = ( + "server_nonce", + "server_public_keyshare", + "server_mac", + "evaluated_message", + "masking_nonce", + "masked_response", + ) + SERVER_NONCE_FIELD_NUMBER: _ClassVar[int] + SERVER_PUBLIC_KEYSHARE_FIELD_NUMBER: _ClassVar[int] + SERVER_MAC_FIELD_NUMBER: _ClassVar[int] + EVALUATED_MESSAGE_FIELD_NUMBER: _ClassVar[int] + MASKING_NONCE_FIELD_NUMBER: _ClassVar[int] + MASKED_RESPONSE_FIELD_NUMBER: _ClassVar[int] + server_nonce: bytes + server_public_keyshare: bytes + server_mac: bytes + evaluated_message: bytes + masking_nonce: bytes + masked_response: bytes + def __init__( + self, + server_nonce: _Optional[bytes] = ..., + server_public_keyshare: _Optional[bytes] = ..., + server_mac: _Optional[bytes] = ..., + evaluated_message: _Optional[bytes] = ..., + masking_nonce: _Optional[bytes] = ..., + masked_response: _Optional[bytes] = ..., + ) -> None: ... + +class OpaqueLoginRequest(_message.Message): + __slots__ = ("initial_request", "final_request") + INITIAL_REQUEST_FIELD_NUMBER: _ClassVar[int] + FINAL_REQUEST_FIELD_NUMBER: _ClassVar[int] + initial_request: InitialOpaqueLoginRequest + final_request: FinalOpaqueLoginRequest + def __init__( + self, + initial_request: _Optional[_Union[InitialOpaqueLoginRequest, _Mapping]] = ..., + final_request: _Optional[_Union[FinalOpaqueLoginRequest, _Mapping]] = ..., + ) -> None: ... + +class OpaqueLoginResponse(_message.Message): + __slots__ = ("initial_response", "final_response") + class FinalResponse(_message.Message): + __slots__ = () + def __init__(self) -> None: ... + + INITIAL_RESPONSE_FIELD_NUMBER: _ClassVar[int] + FINAL_RESPONSE_FIELD_NUMBER: _ClassVar[int] + initial_response: InitialOpaqueLoginResponse + final_response: OpaqueLoginResponse.FinalResponse + def __init__( + self, + initial_response: _Optional[_Union[InitialOpaqueLoginResponse, _Mapping]] = ..., + final_response: _Optional[ + _Union[OpaqueLoginResponse.FinalResponse, _Mapping] + ] = ..., + ) -> None: ... + +class LoginRequest(_message.Message): + __slots__ = ("username", "opaque_request", "handshake_request") + USERNAME_FIELD_NUMBER: _ClassVar[int] + OPAQUE_REQUEST_FIELD_NUMBER: _ClassVar[int] + HANDSHAKE_REQUEST_FIELD_NUMBER: _ClassVar[int] + username: str + opaque_request: OpaqueLoginRequest + handshake_request: _authentication_pb2.PasswordAuthenticationHandshakeRequest + def __init__( + self, + username: _Optional[str] = ..., + opaque_request: _Optional[_Union[OpaqueLoginRequest, _Mapping]] = ..., + handshake_request: _Optional[ + _Union[_authentication_pb2.PasswordAuthenticationHandshakeRequest, _Mapping] + ] = ..., + ) -> None: ... + +class LoginResponse(_message.Message): + __slots__ = ("access_token", "opaque_response", "handshake_response") + ACCESS_TOKEN_FIELD_NUMBER: _ClassVar[int] + OPAQUE_RESPONSE_FIELD_NUMBER: _ClassVar[int] + HANDSHAKE_RESPONSE_FIELD_NUMBER: _ClassVar[int] + access_token: AccessToken + opaque_response: OpaqueLoginResponse + handshake_response: _authentication_pb2.PasswordAuthenticationHandshakeResponse + def __init__( + self, + access_token: _Optional[_Union[AccessToken, _Mapping]] = ..., + opaque_response: _Optional[_Union[OpaqueLoginResponse, _Mapping]] = ..., + handshake_response: _Optional[ + _Union[ + _authentication_pb2.PasswordAuthenticationHandshakeResponse, _Mapping + ] + ] = ..., + ) -> None: ... diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2_grpc.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2_grpc.py new file mode 100644 index 000000000000..18cc0685b2c2 --- /dev/null +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/omni/proto/login_pb2_grpc.py @@ -0,0 +1,109 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" + +import grpc + +from google.cloud.spanner_v1.omni.proto import ( + login_pb2 as google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_login__pb2, +) + +GRPC_GENERATED_VERSION = "1.59.0" +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + + _version_not_supported = first_version_is_lower( + GRPC_VERSION, GRPC_GENERATED_VERSION + ) +except ImportError: + _version_not_supported = False + +if _version_not_supported: + raise RuntimeError( + f"The grpc package installed is at version {GRPC_VERSION}," + + " but the generated code in google/cloud/spanner_v1/omni/proto/login_pb2_grpc.py depends on" + + f" grpcio>={GRPC_GENERATED_VERSION}." + + f" Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}" + + f" or downgrade your generated code using grpcio-tools<={GRPC_VERSION}." + ) + + +class LoginServiceStub: + """The LoginService is used to authenticate users.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Login = channel.stream_stream( + "/google.spanner.auth.v1.LoginService/Login", + request_serializer=google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_login__pb2.LoginRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_login__pb2.LoginResponse.FromString, + _registered_method=True, + ) + + +class LoginServiceServicer: + """The LoginService is used to authenticate users.""" + + def Login(self, request_iterator, context): + """Performs the login for Spanner Omni.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + +def add_LoginServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + "Login": grpc.stream_stream_rpc_method_handler( + servicer.Login, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_login__pb2.LoginRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_login__pb2.LoginResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + "google.spanner.auth.v1.LoginService", rpc_method_handlers + ) + server.add_generic_rpc_handlers((generic_handler,)) + server.add_registered_method_handlers( + "google.spanner.auth.v1.LoginService", rpc_method_handlers + ) + + +# This class is part of an EXPERIMENTAL API. +class LoginService: + """The LoginService is used to authenticate users.""" + + @staticmethod + def Login( + request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.stream_stream( + request_iterator, + target, + "/google.spanner.auth.v1.LoginService/Login", + google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_login__pb2.LoginRequest.SerializeToString, + google_dot_cloud_dot_spanner__v1_dot_omni_dot_proto_dot_login__pb2.LoginResponse.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True, + ) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/pool.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/pool.py index 80cc7ed2d7aa..74dbfa9e60ae 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/pool.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/pool.py @@ -81,8 +81,7 @@ class AbstractSessionPool(object): by the pool. :type database_role: str - :param database_role: (Optional) user-assigned database_role for the session. - """ + :param database_role: (Optional) user-assigned database_role for the session.""" _database = None @@ -224,8 +223,7 @@ class FixedSizePool(AbstractSessionPool): by the pool. :type database_role: str - :param database_role: (Optional) user-assigned database_role for the session. - """ + :param database_role: (Optional) user-assigned database_role for the session.""" DEFAULT_SIZE = 10 DEFAULT_TIMEOUT = 10 @@ -441,8 +439,7 @@ class BurstyPool(AbstractSessionPool): by the pool. :type database_role: str - :param database_role: (Optional) user-assigned database_role for the session. - """ + :param database_role: (Optional) user-assigned database_role for the session.""" def __init__(self, target_size=10, labels=None, database_role=None): super(BurstyPool, self).__init__(labels=labels, database_role=database_role) @@ -556,8 +553,7 @@ class PingingPool(FixedSizePool): by the pool. :type database_role: str - :param database_role: (Optional) user-assigned database_role for the session. - """ + :param database_role: (Optional) user-assigned database_role for the session.""" def __init__( self, @@ -767,8 +763,7 @@ class TransactionPingingPool(PingingPool): by the pool. :type database_role: str - :param database_role: (Optional) user-assigned database_role for the session. - """ + :param database_role: (Optional) user-assigned database_role for the session.""" def __init__( self, diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/session.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/session.py index 308c5d323624..9c1cb6ea1984 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/session.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/session.py @@ -70,8 +70,7 @@ class Session(object): :param database_role: (Optional) user-assigned database_role for the session. :type is_multiplexed: bool - :param is_multiplexed: (Optional) whether this session is a multiplexed session. - """ + :param is_multiplexed: (Optional) whether this session is a multiplexed session.""" def __init__(self, database, labels=None, database_role=None, is_multiplexed=False): self._database = database diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/snapshot.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/snapshot.py index 3d30e308c72a..ce2bd07306d8 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/snapshot.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/snapshot.py @@ -18,7 +18,6 @@ """Model a set of read-only queries to a database as a snapshot.""" import functools -import threading from typing import List, Optional, Union from google.api_core import gapic_v1 @@ -70,6 +69,7 @@ "RST_STREAM", "Received unexpected EOS on DATA frame from server", ) +_TRANSACTION_BEGIN_TIMEOUT_SECONDS = 30.0 def _restart_on_unavailable( @@ -98,8 +98,7 @@ def _restart_on_unavailable( :type transaction_selector: :class:`transaction_pb2.TransactionSelector` :param transaction_selector: Transaction selector object to be used in request if transaction is not passed, - if both transaction_selector and transaction are passed, then transaction is given priority. - """ + if both transaction_selector and transaction are passed, then transaction is given priority.""" resume_token: bytes = b"" item_buffer: List[PartialResultSet] = [] if transaction is not None: @@ -126,11 +125,10 @@ def _restart_on_unavailable( ) as span, MetricsCapture(resource_info), ): - ( - call_metadata, - current_request_id, - ) = request_id_manager.metadata_and_request_id( - nth_request, attempt, metadata, span + call_metadata, current_request_id = ( + request_id_manager.metadata_and_request_id( + nth_request, attempt, metadata, span + ) ) iterator = CrossSync._Sync_Impl.run_if_async( method, request=request, metadata=call_metadata @@ -202,19 +200,12 @@ def __init__(self, session, client_context=None): self._execute_sql_request_count: int = 0 self._read_request_count: int = 0 self._begin_request_sent: bool = False - - # Identifier for the transaction. self._transaction_id: Optional[bytes] = None self._precommit_token: Optional[MultiplexedSessionPrecommitToken] = None self._lock: CrossSync._Sync_Impl.Lock = CrossSync._Sync_Impl.Lock() - - # Operation within a transaction can be performed using multiple - # threads, so we need to use a lock when updating the transaction. - self._lock: threading.Lock = threading.Lock() - - # Event to coordinate concurrent requests beginning the transaction. - # This is used to prevent the "Transaction has not begun" race condition. - self._transaction_begin_event = threading.Event() + self._transaction_begin_event: CrossSync._Sync_Impl.Event = ( + CrossSync._Sync_Impl.Event() + ) @property def _resource_info(self): @@ -226,6 +217,33 @@ def _resource_info(self): "database": database.database_id, } + def _wait_for_transaction_begin(self) -> None: + """Claims the inline-begin for this request, or waits for it to complete. + + The first request against the transaction is the one that begins it + inline. Requests that are issued concurrently, before the transaction + id is available, must wait for that first request to complete instead + of assuming that the transaction has not begun. + + :raises ValueError: if the transaction has already been used to execute + a request, but is not a multi-use transaction, or if the concurrent + request that began the transaction did not complete in time.""" + with self._lock: + if self._begin_request_sent or self._read_request_count > 0: + if not self._multi_use: + raise ValueError("Cannot re-use single-use snapshot.") + wait_needed = self._transaction_id is None + else: + wait_needed = False + self._begin_request_sent = True + if not wait_needed: + return + CrossSync._Sync_Impl.event_wait( + self._transaction_begin_event, timeout=_TRANSACTION_BEGIN_TIMEOUT_SECONDS + ) + if not self._transaction_begin_event.is_set(): + raise ValueError("Timed out waiting for transaction to begin.") + def begin(self) -> bytes: """Begins a transaction on the database. @@ -330,31 +348,8 @@ def read( :returns: a result set instance which can be used to consume rows. :raises ValueError: if the Transaction already used to execute a - read request, but is not a multi-use transaction or has not begun. - """ - - with self._lock: - # Check if this request is beginning the transaction. - # If a request is already in progress, other requests must wait - # until the transaction ID is available. - if self._begin_request_sent or self._read_request_count > 0: - if not self._multi_use: - raise ValueError("Cannot re-use single-use snapshot.") - if self._transaction_id is None: - wait_needed = True - else: - wait_needed = False - else: - wait_needed = False - self._begin_request_sent = True - - if wait_needed: - # Wait for the transaction to begin (set by another concurrent request). - # This prevents the race condition where concurrent requests think - # the transaction hasn't begun. - if not self._transaction_begin_event.wait(timeout=30.0): - raise ValueError("Timed out waiting for transaction to begin.") - + read request, but is not a multi-use transaction or has not begun.""" + self._wait_for_transaction_begin() session = self._session database = session._database api = database.spanner_api @@ -526,31 +521,8 @@ def execute_sql( specific column in the given row. :raises ValueError: if the Transaction already used to execute a - read request, but is not a multi-use transaction or has not begun. - """ - - with self._lock: - # Check if this request is beginning the transaction. - # If a request is already in progress, other requests must wait - # until the transaction ID is available. - if self._begin_request_sent or self._read_request_count > 0: - if not self._multi_use: - raise ValueError("Cannot re-use single-use snapshot.") - if self._transaction_id is None: - wait_needed = True - else: - wait_needed = False - else: - wait_needed = False - self._begin_request_sent = True - - if wait_needed: - # Wait for the transaction to begin (set by another concurrent request). - # This prevents the race condition where concurrent requests think - # the transaction hasn't begun. - if not self._transaction_begin_event.wait(timeout=30.0): - raise ValueError("Timed out waiting for transaction to begin.") - + read request, but is not a multi-use transaction or has not begun.""" + self._wait_for_transaction_begin() if params is not None: params_pb = Struct( fields={key: _make_value_pb(value) for key, value in params.items()} @@ -910,9 +882,7 @@ def _update_for_transaction_pb(self, transaction_pb: Transaction) -> None: """Updates the snapshot for the given transaction.""" if self._transaction_id is None and transaction_pb.id: self._transaction_id = transaction_pb.id - # Notify waiting threads that the transaction has begun. self._transaction_begin_event.set() - if transaction_pb._pb.HasField("precommit_token"): self._update_for_precommit_token_pb_unsafe(transaction_pb.precommit_token) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/snapshot_helpers.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/snapshot_helpers.py deleted file mode 100644 index 5e1d6840665a..000000000000 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/snapshot_helpers.py +++ /dev/null @@ -1,730 +0,0 @@ -# Copyright 2016 Google LLC All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -# This file is automatically generated by CrossSync. Do not edit manually. - -"""Model a set of read-only queries to a database as a snapshot.""" - -import functools -from typing import List, Optional, Union - -from google.api_core import gapic_v1 -from google.api_core.exceptions import ( - Aborted, - InternalServerError, - InvalidArgument, - ServiceUnavailable, -) -from google.protobuf.struct_pb2 import Struct - -from google.cloud.aio._cross_sync import CrossSync -from google.cloud.spanner_v1._helpers import ( - AtomicCounter, - _augment_error_with_request_id, - _check_rst_stream_error, - _make_value_pb, - _merge_query_options, - _metadata_with_leader_aware_routing, - _metadata_with_prefix, - _retry, - _SessionWrapper, -) -from google.cloud.spanner_v1._opentelemetry_tracing import add_span_event, trace_call -from google.cloud.spanner_v1.metrics.metrics_capture import MetricsCapture -from google.cloud.spanner_v1.streamed import StreamedResultSet -from google.cloud.spanner_v1.types import MultiplexedSessionPrecommitToken -from google.cloud.spanner_v1.types.mutation import Mutation -from google.cloud.spanner_v1.types.result_set import PartialResultSet, ResultSet -from google.cloud.spanner_v1.types.spanner import ( - BeginTransactionRequest, - ExecuteSqlRequest, - PartitionOptions, - PartitionQueryRequest, - PartitionReadRequest, - ReadRequest, - RequestOptions, -) -from google.cloud.spanner_v1.types.transaction import ( - Transaction, - TransactionOptions, - TransactionSelector, -) - -_STREAM_RESUMPTION_INTERNAL_ERROR_MESSAGES = ( - "RST_STREAM", - "Received unexpected EOS on DATA frame from server", -) - - -def _restart_on_unavailable( - method, - request, - metadata=None, - trace_name=None, - session=None, - attributes=None, - transaction=None, - transaction_selector=None, - observability_options=None, - request_id_manager=None, -): - """Restart iteration after :exc:`.ServiceUnavailable`. - - :type method: callable - :param method: function returning iterator - - :type request: proto - :param request: request proto to call the method with - - :type transaction: :class:`google.cloud.spanner_v1.snapshot._SnapshotBase` - :param transaction: Snapshot or Transaction class object based on the type of transaction - - :type transaction_selector: :class:`transaction_pb2.TransactionSelector` - :param transaction_selector: Transaction selector object to be used in request if transaction is not passed, - if both transaction_selector and transaction are passed, then transaction is given priority. - """ - resume_token: bytes = b"" - item_buffer: List[PartialResultSet] = [] - if transaction is not None: - transaction_selector = transaction._build_transaction_selector_pb() - elif transaction_selector is None: - raise InvalidArgument( - "Either transaction or transaction_selector should be set" - ) - request.transaction = transaction_selector - iterator = None - attempt = 1 - nth_request = getattr(request_id_manager, "_next_nth_request", 0) - current_request_id = None - while True: - try: - if iterator is None: - with ( - trace_call( - trace_name, - session, - attributes, - observability_options=observability_options, - metadata=metadata, - ) as span, - MetricsCapture(), - ): - ( - call_metadata, - current_request_id, - ) = request_id_manager.metadata_and_request_id( - nth_request, attempt, metadata, span - ) - iterator = CrossSync._Sync_Impl.run_if_async( - method, request=request, metadata=call_metadata - ) - item: PartialResultSet - for item in iterator: - item_buffer.append(item) - if transaction is not None: - transaction._update_for_result_set_pb(item) - if ( - item._pb is not None - and item._pb.HasField("precommit_token") - and (transaction is not None) - ): - transaction._update_for_precommit_token_pb(item.precommit_token) - if item.resume_token: - resume_token = item.resume_token - break - except ServiceUnavailable: - del item_buffer[:] - request.resume_token = resume_token - if transaction is not None: - transaction_selector = transaction._build_transaction_selector_pb() - request.transaction = transaction_selector - attempt += 1 - iterator = None - continue - except InternalServerError as exc: - resumable_error = any( - ( - resumable_message in exc.message - for resumable_message in _STREAM_RESUMPTION_INTERNAL_ERROR_MESSAGES - ) - ) - if not resumable_error: - raise _augment_error_with_request_id(exc, current_request_id) - del item_buffer[:] - request.resume_token = resume_token - if transaction is not None: - transaction_selector = transaction._build_transaction_selector_pb() - attempt += 1 - request.transaction = transaction_selector - iterator = None - continue - except Exception as exc: - raise _augment_error_with_request_id(exc, current_request_id) - if len(item_buffer) == 0: - break - for item in item_buffer: - yield item - del item_buffer[:] - - -class _SnapshotBase(_SessionWrapper): - """Base class for Snapshot. - - Allows reuse of API request methods with different transaction selector. - - :type session: :class:`~google.cloud.spanner_v1.session.Session` - :param session: the session used to perform transaction operations. - """ - - _read_only: bool = True - _multi_use: bool = False - - def __init__(self, session): - super().__init__(session) - self._execute_sql_request_count: int = 0 - self._read_request_count: int = 0 - self._transaction_id: Optional[bytes] = None - self._precommit_token: Optional[MultiplexedSessionPrecommitToken] = None - self._lock: CrossSync._Sync_Impl.Lock = CrossSync._Sync_Impl.Lock() - - def begin(self) -> bytes: - """Begins a transaction on the database. - - :rtype: bytes - :returns: identifier for the transaction. - - :raises ValueError: if the transaction has already begun.""" - return self._begin_transaction() - - def read( - self, - table, - columns, - keyset, - index="", - limit=0, - partition=None, - request_options=None, - data_boost_enabled=False, - directed_read_options=None, - *, - retry=gapic_v1.method.DEFAULT, - timeout=gapic_v1.method.DEFAULT, - column_info=None, - lazy_decode=False, - ): - """Perform a ``StreamingRead`` API request for rows in a table.""" - if self._read_request_count > 0: - if not self._multi_use: - raise ValueError("Cannot re-use single-use snapshot.") - if self._transaction_id is None: - raise ValueError("Transaction has not begun.") - session = self._session - database = session._database - api = database.spanner_api - metadata = _metadata_with_prefix(database.name) - if not self._read_only and database._route_to_leader_enabled: - metadata.append( - _metadata_with_leader_aware_routing(database._route_to_leader_enabled) - ) - if request_options is None: - request_options = RequestOptions() - elif type(request_options) is dict: - request_options = RequestOptions(request_options) - if self._read_only: - request_options.transaction_tag = None - if ( - directed_read_options is None - and database._directed_read_options is not None - ): - directed_read_options = database._directed_read_options - elif self.transaction_tag is not None: - request_options.transaction_tag = self.transaction_tag - read_request = ReadRequest( - session=session.name, - table=table, - columns=columns, - key_set=keyset._to_pb(), - index=index, - limit=limit, - partition_token=partition, - request_options=request_options, - data_boost_enabled=data_boost_enabled, - directed_read_options=directed_read_options, - ) - streaming_read_method = functools.partial( - api.streaming_read, - request=read_request, - metadata=metadata, - retry=retry, - timeout=timeout, - ) - return self._get_streamed_result_set( - method=streaming_read_method, - request=read_request, - metadata=metadata, - trace_attributes={ - "table_id": table, - "columns": columns, - "request_options": request_options, - }, - column_info=column_info, - lazy_decode=lazy_decode, - ) - - def execute_sql( - self, - sql, - params=None, - param_types=None, - query_mode=None, - query_options=None, - request_options=None, - last_statement=False, - partition=None, - retry=gapic_v1.method.DEFAULT, - timeout=gapic_v1.method.DEFAULT, - data_boost_enabled=False, - directed_read_options=None, - column_info=None, - lazy_decode=False, - ): - """Perform an ``ExecuteStreamingSql`` API request.""" - if self._read_request_count > 0: - if not self._multi_use: - raise ValueError("Cannot re-use single-use snapshot.") - if self._transaction_id is None: - raise ValueError("Transaction has not begun.") - if params is not None: - params_pb = Struct( - fields={key: _make_value_pb(value) for key, value in params.items()} - ) - else: - params_pb = {} - session = self._session - database = session._database - api = database.spanner_api - metadata = _metadata_with_prefix(database.name) - if not self._read_only and database._route_to_leader_enabled: - metadata.append( - _metadata_with_leader_aware_routing(database._route_to_leader_enabled) - ) - default_query_options = database._instance._client._query_options - query_options = _merge_query_options(default_query_options, query_options) - if request_options is None: - request_options = RequestOptions() - elif type(request_options) is dict: - request_options = RequestOptions(request_options) - if self._read_only: - request_options.transaction_tag = None - if ( - directed_read_options is None - and database._directed_read_options is not None - ): - directed_read_options = database._directed_read_options - elif self.transaction_tag is not None: - request_options.transaction_tag = self.transaction_tag - execute_sql_request = ExecuteSqlRequest( - session=session.name, - sql=sql, - params=params_pb, - param_types=param_types, - query_mode=query_mode, - partition_token=partition, - seqno=self._execute_sql_request_count, - query_options=query_options, - request_options=request_options, - last_statement=last_statement, - data_boost_enabled=data_boost_enabled, - directed_read_options=directed_read_options, - ) - execute_streaming_sql_method = functools.partial( - api.execute_streaming_sql, - request=execute_sql_request, - metadata=metadata, - retry=retry, - timeout=timeout, - ) - return self._get_streamed_result_set( - method=execute_streaming_sql_method, - request=execute_sql_request, - metadata=metadata, - trace_attributes={"db.statement": sql, "request_options": request_options}, - column_info=column_info, - lazy_decode=lazy_decode, - ) - - def _get_streamed_result_set( - self, method, request, metadata, trace_attributes, column_info, lazy_decode - ): - """Returns the streamed result set for a read or execute SQL request.""" - session = self._session - database = session._database - is_execute_sql_request = isinstance(request, ExecuteSqlRequest) - trace_method_name = "execute_sql" if is_execute_sql_request else "read" - trace_name = f"CloudSpanner.{type(self).__name__}.{trace_method_name}" - is_inline_begin = False - if self._transaction_id is None: - is_inline_begin = True - self._lock.acquire() - try: - iterator = _restart_on_unavailable( - method=method, - request=request, - session=session, - metadata=metadata, - trace_name=trace_name, - attributes=trace_attributes, - transaction=self, - observability_options=getattr(database, "observability_options", None), - request_id_manager=database, - ) - if is_execute_sql_request: - self._execute_sql_request_count += 1 - self._read_request_count += 1 - streamed_result_set_args = { - "response_iterator": iterator, - "column_info": column_info, - "lazy_decode": lazy_decode, - } - if self._multi_use: - streamed_result_set_args["source"] = self - return StreamedResultSet(**streamed_result_set_args) - finally: - if is_inline_begin: - self._lock.release() - - def partition_read( - self, - table, - columns, - keyset, - index="", - partition_size_bytes=None, - max_partitions=None, - *, - retry=gapic_v1.method.DEFAULT, - timeout=gapic_v1.method.DEFAULT, - ): - """Perform a ``PartitionRead`` API request for rows in a table.""" - if self._transaction_id is None: - raise ValueError("Transaction has not begun.") - if not self._multi_use: - raise ValueError("Cannot partition a single-use transaction.") - session = self._session - database = session._database - api = database.spanner_api - metadata = _metadata_with_prefix(database.name) - if database._route_to_leader_enabled: - metadata.append( - _metadata_with_leader_aware_routing(database._route_to_leader_enabled) - ) - transaction = self._build_transaction_selector_pb() - partition_options = PartitionOptions( - partition_size_bytes=partition_size_bytes, max_partitions=max_partitions - ) - partition_read_request = PartitionReadRequest( - session=session.name, - table=table, - columns=columns, - key_set=keyset._to_pb(), - transaction=transaction, - index=index, - partition_options=partition_options, - ) - trace_attributes = {"table_id": table, "columns": columns} - can_include_index = index != "" and index is not None - if can_include_index: - trace_attributes["index"] = index - with ( - trace_call( - f"CloudSpanner.{type(self).__name__}.partition_read", - session, - extra_attributes=trace_attributes, - observability_options=getattr(database, "observability_options", None), - metadata=metadata, - ) as span, - MetricsCapture(), - ): - nth_request = getattr(database, "_next_nth_request", 0) - attempt = AtomicCounter() - - def attempt_tracking_method(): - all_metadata = database.metadata_with_request_id( - nth_request, attempt.increment(), metadata, span - ) - partition_read_method = functools.partial( - api.partition_read, - request=partition_read_request, - metadata=all_metadata, - retry=retry, - timeout=timeout, - ) - return partition_read_method() - - response = _retry( - attempt_tracking_method, - allowed_exceptions={InternalServerError: _check_rst_stream_error}, - ) - return [partition.partition_token for partition in response.partitions] - - def partition_query( - self, - sql, - params=None, - param_types=None, - partition_size_bytes=None, - max_partitions=None, - *, - retry=gapic_v1.method.DEFAULT, - timeout=gapic_v1.method.DEFAULT, - ): - """Perform a ``PartitionQuery`` API request.""" - if self._transaction_id is None: - raise ValueError("Transaction has not begun.") - if not self._multi_use: - raise ValueError("Cannot partition a single-use transaction.") - if params is not None: - params_pb = Struct( - fields={key: _make_value_pb(value) for key, value in params.items()} - ) - else: - params_pb = Struct() - session = self._session - database = session._database - api = database.spanner_api - metadata = _metadata_with_prefix(database.name) - if database._route_to_leader_enabled: - metadata.append( - _metadata_with_leader_aware_routing(database._route_to_leader_enabled) - ) - transaction = self._build_transaction_selector_pb() - partition_options = PartitionOptions( - partition_size_bytes=partition_size_bytes, max_partitions=max_partitions - ) - partition_query_request = PartitionQueryRequest( - session=session.name, - sql=sql, - transaction=transaction, - params=params_pb, - param_types=param_types, - partition_options=partition_options, - ) - trace_attributes = {"db.statement": sql} - with ( - trace_call( - f"CloudSpanner.{type(self).__name__}.partition_query", - session, - trace_attributes, - observability_options=getattr(database, "observability_options", None), - metadata=metadata, - ) as span, - MetricsCapture(), - ): - nth_request = getattr(database, "_next_nth_request", 0) - attempt = AtomicCounter() - - def attempt_tracking_method(): - all_metadata = database.metadata_with_request_id( - nth_request, attempt.increment(), metadata, span - ) - partition_query_method = functools.partial( - api.partition_query, - request=partition_query_request, - metadata=all_metadata, - retry=retry, - timeout=timeout, - ) - return partition_query_method() - - response = _retry( - attempt_tracking_method, - allowed_exceptions={InternalServerError: _check_rst_stream_error}, - ) - return [partition.partition_token for partition in response.partitions] - - def _begin_transaction( - self, mutation: Mutation = None, transaction_tag: str = None - ) -> bytes: - """Begins a transaction on the database.""" - if self._transaction_id is not None: - raise ValueError("Transaction has already begun.") - if not self._multi_use: - raise ValueError("Cannot begin a single-use transaction.") - if self._read_request_count > 0: - raise ValueError("Read-only transaction already pending") - session = self._session - database = session._database - api = database.spanner_api - metadata = _metadata_with_prefix(database.name) - if not self._read_only and database._route_to_leader_enabled: - metadata.append( - _metadata_with_leader_aware_routing(database._route_to_leader_enabled) - ) - begin_request_kwargs = { - "session": session.name, - "options": self._build_transaction_selector_pb().begin, - "mutation_key": mutation, - } - if transaction_tag: - begin_request_kwargs["request_options"] = RequestOptions( - transaction_tag=transaction_tag - ) - with ( - trace_call( - name=f"CloudSpanner.{type(self).__name__}.begin", - session=session, - observability_options=getattr(database, "observability_options", None), - metadata=metadata, - ) as span, - MetricsCapture(), - ): - nth_request = getattr(database, "_next_nth_request", 0) - attempt = AtomicCounter() - - def wrapped_method(): - begin_transaction_request = BeginTransactionRequest( - **begin_request_kwargs - ) - call_metadata, error_augmenter = database.with_error_augmentation( - nth_request, attempt.increment(), metadata, span - ) - begin_transaction_method = functools.partial( - api.begin_transaction, - request=begin_transaction_request, - metadata=call_metadata, - ) - with error_augmenter: - return begin_transaction_method() - - def before_next_retry(nth_retry, delay_in_seconds): - add_span_event( - span=span, - event_name="Transaction Begin Attempt Failed. Retrying", - event_attributes={ - "attempt": nth_retry, - "sleep_seconds": delay_in_seconds, - }, - ) - - transaction_pb: Transaction = _retry( - wrapped_method, - before_next_retry=before_next_retry, - allowed_exceptions={ - InternalServerError: _check_rst_stream_error, - Aborted: None, - }, - ) - self._update_for_transaction_pb(transaction_pb) - return self._transaction_id - - def _build_transaction_options_pb(self) -> TransactionOptions: - """Builds and returns the transaction options for this snapshot.""" - raise NotImplementedError - - def _build_transaction_selector_pb(self) -> TransactionSelector: - """Builds and returns a transaction selector for this snapshot.""" - if self._transaction_id is not None: - return TransactionSelector(id=self._transaction_id) - options = self._build_transaction_options_pb() - if not self._multi_use: - return TransactionSelector(single_use=options) - return TransactionSelector(begin=options) - - def _update_for_result_set_pb( - self, result_set_pb: Union[ResultSet, PartialResultSet] - ) -> None: - """Updates the snapshot for the given result set.""" - if result_set_pb.metadata and result_set_pb.metadata.transaction: - self._update_for_transaction_pb(result_set_pb.metadata.transaction) - - def _update_for_transaction_pb(self, transaction_pb: Transaction) -> None: - """Updates the snapshot for the given transaction.""" - if self._transaction_id is None and transaction_pb.id: - self._transaction_id = transaction_pb.id - if transaction_pb._pb.HasField("precommit_token"): - self._update_for_precommit_token_pb_unsafe(transaction_pb.precommit_token) - - def _update_for_precommit_token_pb( - self, precommit_token_pb: MultiplexedSessionPrecommitToken - ) -> None: - """Updates the snapshot for the given multiplexed session precommit token.""" - with self._lock: - self._update_for_precommit_token_pb_unsafe(precommit_token_pb) - - def _update_for_precommit_token_pb_unsafe( - self, precommit_token_pb: MultiplexedSessionPrecommitToken - ) -> None: - """Updates the snapshot for the given multiplexed session precommit token.""" - if ( - self._precommit_token is None - or precommit_token_pb.seq_num > self._precommit_token.seq_num - ): - self._precommit_token = precommit_token_pb - - -class Snapshot(_SnapshotBase): - """Allow a set of reads / SQL statements with shared staleness.""" - - def __init__( - self, - session, - read_timestamp=None, - min_read_timestamp=None, - max_staleness=None, - exact_staleness=None, - multi_use=False, - transaction_id=None, - ): - super(Snapshot, self).__init__(session) - opts = [read_timestamp, min_read_timestamp, max_staleness, exact_staleness] - flagged = [opt for opt in opts if opt is not None] - if len(flagged) > 1: - raise ValueError("Supply zero or one options.") - if multi_use: - if min_read_timestamp is not None or max_staleness is not None: - raise ValueError( - "'multi_use' is incompatible with 'min_read_timestamp' / 'max_staleness'" - ) - self._transaction_read_timestamp = None - self._strong = len(flagged) == 0 - self._read_timestamp = read_timestamp - self._min_read_timestamp = min_read_timestamp - self._max_staleness = max_staleness - self._exact_staleness = exact_staleness - self._multi_use = multi_use - self._transaction_id = transaction_id - - def _build_transaction_options_pb(self) -> TransactionOptions: - """Builds and returns transaction options for this snapshot.""" - read_only_pb_args = dict(return_read_timestamp=True) - if self._read_timestamp: - read_only_pb_args["read_timestamp"] = self._read_timestamp - elif self._min_read_timestamp: - read_only_pb_args["min_read_timestamp"] = self._min_read_timestamp - elif self._max_staleness: - read_only_pb_args["max_staleness"] = self._max_staleness - elif self._exact_staleness: - read_only_pb_args["exact_staleness"] = self._exact_staleness - else: - read_only_pb_args["strong"] = True - read_only_pb = TransactionOptions.ReadOnly(**read_only_pb_args) - return TransactionOptions(read_only=read_only_pb) - - def _update_for_transaction_pb(self, transaction_pb: Transaction) -> None: - """Updates the snapshot for the given transaction.""" - super(Snapshot, self)._update_for_transaction_pb(transaction_pb) - if transaction_pb.read_timestamp is not None: - self._transaction_read_timestamp = transaction_pb.read_timestamp diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/streamed.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/streamed.py index a92f008f5e32..d95705af038a 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/streamed.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/streamed.py @@ -111,6 +111,11 @@ def _merge_chunk(self, value): def _merge_values(self, values): """Merge values into rows. + Note: We manually check value.HasField("null_value") here instead of + wrapping every decoder in _parse_nullable to avoid the overhead of + an extra Python function call layer for every cell value decoded in this loop. + If the nullable check logic is updated in _parse_nullable, update this check. + :type values: list of :class:`~google.protobuf.struct_pb2.Value` :param values: non-chunked values from partial result set.""" decoders = self._decoders @@ -131,10 +136,6 @@ def _merge_values(self, values): index = 0 else: for value in values: - # Note: We manually check value.HasField("null_value") here instead of - # wrapping every decoder in _parse_nullable to avoid the overhead of - # an extra Python function call layer for every cell value decoded in this loop. - # If the nullable check logic is updated in _parse_nullable, update this check. if value.HasField("null_value"): current_row_append(None) else: @@ -184,8 +185,7 @@ def decode_row(self, row: []) -> []: The array that is returned by this function is the same as the array that would have been returned by the rows iterator if ``lazy_decoding=False``. - :returns: an array containing the decoded values of all the columns in the given row - """ + :returns: an array containing the decoded values of all the columns in the given row""" if not hasattr(row, "__len__"): raise TypeError("row", "row must be an array of protobuf values") decoders = self._decoders diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/database_test.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/database_test.py index 523946ab3545..6018fcdeecdd 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/database_test.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/database_test.py @@ -103,6 +103,7 @@ def spanner_api(self): client._client_certificate, client._client_key, self._interceptors, + credentials=client.credentials, ) self._spanner_api = SpannerClient( client_info=client_info, @@ -119,10 +120,9 @@ def spanner_api(self): return self._spanner_api def _create_spanner_client_for_tests(self, client_options, credentials): - ( - api_endpoint, - client_cert_source_func, - ) = SpannerClient.get_mtls_endpoint_and_cert_source(client_options) + api_endpoint, client_cert_source_func = ( + SpannerClient.get_mtls_endpoint_and_cert_source(client_options) + ) channel = grpc_helpers.create_channel( api_endpoint, credentials=credentials, diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/transaction.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/transaction.py index 5ba207f07d49..1bd8d01d348d 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/transaction.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/transaction.py @@ -60,8 +60,7 @@ class Transaction(_SnapshotBase, _BatchBase): :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session used to perform the commit - :raises ValueError: if session has an existing transaction - """ + :raises ValueError: if session has an existing transaction""" exclude_txn_from_change_streams: bool = False isolation_level: TransactionOptions.IsolationLevel = ( @@ -447,46 +446,48 @@ def execute_update( if self._transaction_id is None: is_inline_begin = True self._lock.acquire() - execute_sql_request = ExecuteSqlRequest( - session=session.name, - transaction=self._build_transaction_selector_pb(), - sql=dml, - params=params_pb, - param_types=param_types, - query_mode=query_mode, - query_options=query_options, - seqno=seqno, - request_options=request_options, - last_statement=last_statement, - ) - nth_request = database._next_nth_request - attempt = AtomicCounter(0) - - def wrapped_method(*args, **kwargs): - attempt.increment() - call_metadata, error_augmenter = database.with_error_augmentation( - nth_request, attempt.value, metadata + try: + execute_sql_request = ExecuteSqlRequest( + session=session.name, + transaction=self._build_transaction_selector_pb(), + sql=dml, + params=params_pb, + param_types=param_types, + query_mode=query_mode, + query_options=query_options, + seqno=seqno, + request_options=request_options, + last_statement=last_statement, ) - execute_sql_method = functools.partial( - api.execute_sql, - request=execute_sql_request, - metadata=call_metadata, - retry=retry, - timeout=timeout, + nth_request = database._next_nth_request + attempt = AtomicCounter(0) + + def wrapped_method(*args, **kwargs): + attempt.increment() + call_metadata, error_augmenter = database.with_error_augmentation( + nth_request, attempt.value, metadata + ) + execute_sql_method = functools.partial( + api.execute_sql, + request=execute_sql_request, + metadata=call_metadata, + retry=retry, + timeout=timeout, + ) + with error_augmenter: + return execute_sql_method(*args, **kwargs) + + result_set_pb: ResultSet = self._execute_request( + wrapped_method, + execute_sql_request, + metadata, + f"CloudSpanner.{type(self).__name__}.execute_update", + trace_attributes, ) - with error_augmenter: - return execute_sql_method(*args, **kwargs) - - result_set_pb: ResultSet = self._execute_request( - wrapped_method, - execute_sql_request, - metadata, - f"CloudSpanner.{type(self).__name__}.execute_update", - trace_attributes, - ) - self._update_for_result_set_pb(result_set_pb) - if is_inline_begin: - self._lock.release() + self._update_for_result_set_pb(result_set_pb) + finally: + if is_inline_begin: + self._lock.release() if result_set_pb._pb.HasField("precommit_token"): self._update_for_precommit_token_pb(result_set_pb.precommit_token) return result_set_pb.stats.row_count_exact @@ -587,42 +588,44 @@ def batch_update( if self._transaction_id is None: is_inline_begin = True self._lock.acquire() - execute_batch_dml_request = ExecuteBatchDmlRequest( - session=session.name, - transaction=self._build_transaction_selector_pb(), - statements=parsed, - seqno=seqno, - request_options=request_options, - last_statements=last_statement, - ) - nth_request = database._next_nth_request - attempt = AtomicCounter(0) - - def wrapped_method(*args, **kwargs): - attempt.increment() - call_metadata, error_augmenter = database.with_error_augmentation( - nth_request, attempt.value, metadata + try: + execute_batch_dml_request = ExecuteBatchDmlRequest( + session=session.name, + transaction=self._build_transaction_selector_pb(), + statements=parsed, + seqno=seqno, + request_options=request_options, + last_statements=last_statement, ) - execute_batch_dml_method = functools.partial( - api.execute_batch_dml, - request=execute_batch_dml_request, - metadata=call_metadata, - retry=retry, - timeout=timeout, + nth_request = database._next_nth_request + attempt = AtomicCounter(0) + + def wrapped_method(*args, **kwargs): + attempt.increment() + call_metadata, error_augmenter = database.with_error_augmentation( + nth_request, attempt.value, metadata + ) + execute_batch_dml_method = functools.partial( + api.execute_batch_dml, + request=execute_batch_dml_request, + metadata=call_metadata, + retry=retry, + timeout=timeout, + ) + with error_augmenter: + return execute_batch_dml_method(*args, **kwargs) + + response_pb: ExecuteBatchDmlResponse = self._execute_request( + wrapped_method, + execute_batch_dml_request, + metadata, + "CloudSpanner.DMLTransaction", + trace_attributes, ) - with error_augmenter: - return execute_batch_dml_method(*args, **kwargs) - - response_pb: ExecuteBatchDmlResponse = self._execute_request( - wrapped_method, - execute_batch_dml_request, - metadata, - "CloudSpanner.DMLTransaction", - trace_attributes, - ) - self._update_for_execute_batch_dml_response_pb(response_pb) - if is_inline_begin: - self._lock.release() + self._update_for_execute_batch_dml_response_pb(response_pb) + finally: + if is_inline_begin: + self._lock.release() if ( len(response_pb.result_sets) > 0 and response_pb.result_sets[0].precommit_token @@ -686,8 +689,7 @@ def _update_for_execute_batch_dml_response_pb( """Update the transaction for the given execute batch DML response. :type response_pb: :class:`~google.cloud.spanner_v1.types.ExecuteBatchDmlResponse` - :param response_pb: The execute batch DML response to update the transaction with. - """ + :param response_pb: The execute batch DML response to update the transaction with.""" if len(response_pb.result_sets) > 0: self._update_for_result_set_pb(response_pb.result_sets[0]) diff --git a/packages/google-cloud-spanner/noxfile.py b/packages/google-cloud-spanner/noxfile.py index ff5ebf5d1712..d5ace5135d2f 100644 --- a/packages/google-cloud-spanner/noxfile.py +++ b/packages/google-cloud-spanner/noxfile.py @@ -52,7 +52,9 @@ UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [ + "omni", +] UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} SYSTEM_TEST_STANDARD_DEPENDENCIES: List[str] = [ @@ -66,6 +68,7 @@ SYSTEM_TEST_DEPENDENCIES: List[str] = [] SYSTEM_TEST_EXTRAS: List[str] = [ "tracing", + "omni", ] SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} @@ -757,7 +760,7 @@ def core_deps_from_source(session, protobuf_implementation): """ # Install all dependencies - session.install("-e", ".") + session.install("-e", ".[omni]") # Install dependencies for the unit test environment unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES diff --git a/packages/google-cloud-spanner/setup.py b/packages/google-cloud-spanner/setup.py index b4e8a3908efc..84f25fe1e969 100644 --- a/packages/google-cloud-spanner/setup.py +++ b/packages/google-cloud-spanner/setup.py @@ -64,6 +64,7 @@ ] extras = { "libcst": "libcst >= 0.2.5", + "omni": ["cryptography >= 44.0.0"], "test": [ "pytest", "mock", diff --git a/packages/google-cloud-spanner/testing/constraints-3.10.txt b/packages/google-cloud-spanner/testing/constraints-3.10.txt index 2df6db04da12..97e2463b1398 100644 --- a/packages/google-cloud-spanner/testing/constraints-3.10.txt +++ b/packages/google-cloud-spanner/testing/constraints-3.10.txt @@ -22,3 +22,4 @@ google-cloud-monitoring==2.28.0 mmh3==4.1.0 libcst==0.2.5 googleapis-common-protos==1.69.2 +cryptography==44.0.0 diff --git a/packages/google-cloud-spanner/tests/system/_async/conftest.py b/packages/google-cloud-spanner/tests/system/_async/conftest.py index 0a09a9676074..b01db2579452 100644 --- a/packages/google-cloud-spanner/tests/system/_async/conftest.py +++ b/packages/google-cloud-spanner/tests/system/_async/conftest.py @@ -38,6 +38,8 @@ def spanner_client(): client_key=_helpers.CLIENT_KEY, client_options={"api_endpoint": _helpers.SPANNER_OMNI}, instance_type="omni", + username=_helpers.SPANNER_OMNI_USER, + password=_helpers.SPANNER_OMNI_PASSWORD, ) else: client_options = {"api_endpoint": _helpers.API_ENDPOINT} diff --git a/packages/google-cloud-spanner/tests/system/_helpers.py b/packages/google-cloud-spanner/tests/system/_helpers.py index 1bad9adec3da..57a1e47fb62b 100644 --- a/packages/google-cloud-spanner/tests/system/_helpers.py +++ b/packages/google-cloud-spanner/tests/system/_helpers.py @@ -68,6 +68,11 @@ CLIENT_KEY = os.getenv(CLIENT_KEY_ENVVAR) USE_PLAIN_TEXT = CA_CERTIFICATE is None +SPANNER_OMNI_USER_ENVVAR = "SPANNER_OMNI_USER" +SPANNER_OMNI_USER = os.getenv(SPANNER_OMNI_USER_ENVVAR) +SPANNER_OMNI_PASSWORD_ENVVAR = "SPANNER_OMNI_PASSWORD" +SPANNER_OMNI_PASSWORD = os.getenv(SPANNER_OMNI_PASSWORD_ENVVAR) + SPANNER_OMNI_INSTANCE = "default" DDL_STATEMENTS = ( diff --git a/packages/google-cloud-spanner/tests/system/conftest.py b/packages/google-cloud-spanner/tests/system/conftest.py index 5aaae4b4484d..757068bebaa5 100644 --- a/packages/google-cloud-spanner/tests/system/conftest.py +++ b/packages/google-cloud-spanner/tests/system/conftest.py @@ -124,6 +124,8 @@ def spanner_client(): client_key=_helpers.CLIENT_KEY, client_options={"api_endpoint": _helpers.SPANNER_OMNI}, instance_type="omni", + username=_helpers.SPANNER_OMNI_USER, + password=_helpers.SPANNER_OMNI_PASSWORD, ) else: client_options = {"api_endpoint": _helpers.API_ENDPOINT} diff --git a/packages/google-cloud-spanner/tests/system/test_dbapi.py b/packages/google-cloud-spanner/tests/system/test_dbapi.py index 82aada69e70a..53d9180663f9 100644 --- a/packages/google-cloud-spanner/tests/system/test_dbapi.py +++ b/packages/google-cloud-spanner/tests/system/test_dbapi.py @@ -1502,6 +1502,8 @@ def test_user_agent(self, shared_instance, dbapi_database): ca_certificate=_helpers.CA_CERTIFICATE, client_certificate=_helpers.CLIENT_CERTIFICATE, client_key=_helpers.CLIENT_KEY, + username=_helpers.SPANNER_OMNI_USER, + password=_helpers.SPANNER_OMNI_PASSWORD, ) assert ( conn.instance._client._client_info.user_agent diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_client.py b/packages/google-cloud-spanner/tests/unit/_async/test_client.py index 60bc98addc8e..9bf7a3751a87 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_client.py @@ -936,3 +936,123 @@ async def test_constructor_w_invalid_instance_type_raises_value_error(self): "instance_type must be one of 'cloud' or 'omni'", str(ctx.exception), ) + + @CrossSync.pytest + async def test_constructor_w_omni_username_password(self): + from google.cloud.spanner_v1._async.client import InstanceType + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + password="test_password", + ) + self.assertEqual(client.project, "default") + self.assertEqual(client.instance_type, InstanceType.OMNI) + self.assertEqual(client._host, "omni-host:15000") + self.assertIsInstance(client._credentials, SpannerOmniCredentials) + self.assertEqual(client._credentials.username, "test_user") + self.assertEqual(client._credentials.target, "omni-host:15000") + + @CrossSync.pytest + async def test_constructor_w_omni_partial_credentials_raises_value_error(self): + from google.cloud.spanner_v1._async.client import InstanceType + + with self.assertRaises(ValueError) as ctx: + self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + ) + self.assertIn( + "Both username and password must be specified for Omni authentication", + str(ctx.exception), + ) + + with self.assertRaises(ValueError) as ctx: + self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + password="test_password", + ) + self.assertIn( + "Both username and password must be specified for Omni authentication", + str(ctx.exception), + ) + + @CrossSync.pytest + async def test_constructor_w_username_password_on_cloud_raises_value_error(self): + creds = build_scoped_credentials() + with self.assertRaises(ValueError) as ctx: + self._make_one( + project=self.PROJECT, + credentials=creds, + username="test_user", + password="test_password", + ) + self.assertIn( + "username and password can only be used when instance_type='omni'.", + str(ctx.exception), + ) + + @CrossSync.pytest + async def test_instance_admin_api_omni(self): + from google.cloud.spanner_v1._async.client import InstanceType + + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + password="test_password", + use_plain_text=True, + ) + + inst_module = "google.cloud.spanner_v1._async.client.InstanceAdminClient" + with mock.patch(inst_module) as instance_admin_client: + api = client.instance_admin_api + self.assertIs(api, instance_admin_client.return_value) + instance_admin_client.assert_called_once() + called_kw = instance_admin_client.call_args[1] + self.assertIn("transport", called_kw) + + @CrossSync.pytest + async def test_database_admin_api_omni(self): + from google.cloud.spanner_v1._async.client import InstanceType + + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + password="test_password", + use_plain_text=True, + ) + + db_module = "google.cloud.spanner_v1._async.client.DatabaseAdminClient" + with mock.patch(db_module) as database_admin_client: + api = client.database_admin_api + self.assertIs(api, database_admin_client.return_value) + database_admin_client.assert_called_once() + called_kw = database_admin_client.call_args[1] + self.assertIn("transport", called_kw) + + @CrossSync.pytest + async def test_constructor_w_omni_explicit_credentials_instance(self): + from google.cloud.spanner_v1._async.client import InstanceType + from google.cloud.spanner_v1.omni.credentials import SpannerOmniCredentials + + creds = SpannerOmniCredentials("user", "pass", "omni-host:15000") + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + credentials=creds, + ) + self.assertIs(client._credentials, creds) diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_helpers_extra.py b/packages/google-cloud-spanner/tests/unit/_async/test_helpers_extra.py index c49ada5ec9c6..883fe2840adc 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_helpers_extra.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_helpers_extra.py @@ -141,3 +141,161 @@ async def test_create_experimental_host_transport_errors(self): MUT._create_experimental_host_transport( InstanceAdminGrpcTransport, "host", False, None, None, None ) + + async def test_create_spanner_omni_transport(self): + mock_factory = mock.MagicMock() + + # Plaintext with create_async_auth_interceptors + mock_creds1 = mock.MagicMock() + mock_creds1.create_async_auth_interceptors.return_value = ["interceptor1"] + with mock.patch("grpc.aio.insecure_channel") as mock_insecure: + MUT._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + credentials=mock_creds1, + ) + mock_insecure.assert_called_once_with( + target="localhost:9010", interceptors=["interceptor1"] + ) + + # Credentials with create_async_auth_interceptor returning list and single item + mock_creds2 = mock.MagicMock(spec=["create_async_auth_interceptor"]) + mock_creds2.create_async_auth_interceptor.return_value = ["interceptor2"] + with mock.patch("grpc.aio.insecure_channel") as mock_insecure: + MUT._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + credentials=mock_creds2, + ) + mock_insecure.assert_called_once_with( + target="localhost:9010", interceptors=["interceptor2"] + ) + + mock_creds2.create_async_auth_interceptor.return_value = "single_interceptor" + with mock.patch("grpc.aio.insecure_channel") as mock_insecure: + MUT._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + credentials=mock_creds2, + ) + mock_insecure.assert_called_once_with( + target="localhost:9010", interceptors=["single_interceptor"] + ) + + # Credentials with create_auth_interceptor returning list and single item + mock_creds3 = mock.MagicMock(spec=["create_auth_interceptor"]) + mock_creds3.create_auth_interceptor.return_value = ["interceptor3"] + with mock.patch("grpc.aio.insecure_channel") as mock_insecure: + MUT._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + credentials=mock_creds3, + ) + mock_insecure.assert_called_once_with( + target="localhost:9010", interceptors=["interceptor3"] + ) + + mock_creds3.create_auth_interceptor.return_value = "single_interceptor3" + with mock.patch("grpc.aio.insecure_channel") as mock_insecure: + MUT._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + credentials=mock_creds3, + ) + mock_insecure.assert_called_once_with( + target="localhost:9010", interceptors=["single_interceptor3"] + ) + + # TLS and mTLS + with mock.patch("builtins.open", mock.mock_open(read_data=b"cert_data")): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_creds: + with mock.patch("grpc.aio.secure_channel") as mock_secure: + # TLS only + MUT._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate=None, + client_key=None, + ) + mock_ssl_creds.assert_called_with(root_certificates=b"cert_data") + mock_secure.assert_called_with( + "omni-host:15000", mock_ssl_creds.return_value, interceptors=[] + ) + + # mTLS + MUT._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate="client.pem", + client_key="key.pem", + ) + mock_ssl_creds.assert_called_with( + root_certificates=b"cert_data", + private_key=b"cert_data", + certificate_chain=b"cert_data", + ) + + # Validation errors + with self.assertRaises(ValueError) as cm: + MUT._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate=None, + client_certificate=None, + client_key=None, + ) + self.assertIn("TLS/mTLS connection requires ca_certificate", str(cm.exception)) + + with mock.patch("builtins.open", mock.mock_open(read_data=b"cert_data")): + with self.assertRaises(ValueError) as cm: + MUT._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate="client.pem", + client_key=None, + ) + self.assertIn( + "Both client_certificate and client_key must be provided for mTLS connection", + str(cm.exception), + ) + + with self.assertRaises(ValueError) as cm: + MUT._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate=None, + client_key="key.pem", + ) + self.assertIn( + "Both client_certificate and client_key must be provided for mTLS connection", + str(cm.exception), + ) diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_snapshot.py b/packages/google-cloud-spanner/tests/unit/_async/test_snapshot.py index bc902a6f63d1..e4e8785f2c43 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_snapshot.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_snapshot.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import asyncio import datetime import unittest from datetime import timedelta @@ -71,21 +72,56 @@ def _make_snapshot(self, *args, **kwargs): async def test_read_errors(self): snapshot = self._make_snapshot(_Session(), multi_use=False) snapshot._read_request_count = 1 - with self.assertRaises(ValueError): + with self.assertRaisesRegex(ValueError, "Cannot re-use single-use snapshot."): await snapshot.read(TABLE_NAME, COLUMNS, None) + @mock.patch( + "google.cloud.spanner_v1._async.snapshot._TRANSACTION_BEGIN_TIMEOUT_SECONDS", + 0.01, + ) + async def test_read_w_multi_use_not_begun_times_out(self): + # No concurrent request ever begins the transaction, so this request + # waits for the begin timeout to expire before giving up. snapshot = self._make_snapshot(_Session(), multi_use=True) snapshot._read_request_count = 1 snapshot._transaction_id = None - with self.assertRaises(ValueError): + with self.assertRaisesRegex( + ValueError, "Timed out waiting for transaction to begin." + ): await snapshot.read(TABLE_NAME, COLUMNS, None) async def test_execute_sql_errors(self): snapshot = self._make_snapshot(_Session(), multi_use=False) snapshot._read_request_count = 1 - with self.assertRaises(ValueError): + with self.assertRaisesRegex(ValueError, "Cannot re-use single-use snapshot."): await snapshot.execute_sql(SQL_QUERY) + async def test_wait_for_transaction_begin_waits_for_concurrent_begin(self): + """A concurrent request must wait for the in-flight inline begin. + + Regression test: without the begin event, the second request observes + ``_transaction_id is None`` and wrongly raises "Transaction has not begun." + """ + + snapshot = self._make_snapshot(_Session(), multi_use=True) + + # First request claims the inline begin, but has not completed yet, so + # no transaction id is available. + await snapshot._wait_for_transaction_begin() + self.assertTrue(snapshot._begin_request_sent) + + concurrent_request = asyncio.ensure_future( + snapshot._wait_for_transaction_begin() + ) + + # The concurrent request blocks while the transaction id is unknown. + done, _ = await asyncio.wait([concurrent_request], timeout=0.1) + self.assertEqual(done, set()) + + # Completing the inline begin releases it. + snapshot._update_for_transaction_pb(TransactionPB(id=TXN_ID)) + await asyncio.wait_for(concurrent_request, timeout=10) + async def test_partition_read_ok(self): token_1 = b"TOKEN1" response = PartitionResponse( @@ -695,12 +731,20 @@ async def test_execute_sql_w_partition(self): call_args = api.execute_streaming_sql.call_args self.assertEqual(call_args.kwargs["request"].partition_token, b"token") + @mock.patch( + "google.cloud.spanner_v1._async.snapshot._TRANSACTION_BEGIN_TIMEOUT_SECONDS", + 0.01, + ) async def test_execute_sql_not_begun_error(self): + # No concurrent request ever begins the transaction, so this request + # waits for the begin timeout to expire before giving up. session = _Session() snapshot = self._make_snapshot(session, multi_use=True) snapshot._read_request_count = 1 snapshot._transaction_id = None - with self.assertRaises(ValueError): + with self.assertRaisesRegex( + ValueError, "Timed out waiting for transaction to begin." + ): await snapshot.execute_sql(SQL_QUERY) async def test_execute_sql_w_params(self): diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_transaction.py b/packages/google-cloud-spanner/tests/unit/_async/test_transaction.py index 9e71af613ae4..7b0edeb4d171 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_transaction.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_transaction.py @@ -771,6 +771,25 @@ async def test_execute_update_other_error(self, mock_region): with pytest.raises(RuntimeError): await transaction.execute_update(DML_QUERY) + @mock.patch( + "google.cloud.spanner_v1._opentelemetry_tracing._get_cloud_region", + return_value="global", + ) + @CrossSync.pytest + async def test_execute_update_inline_begin_error_releases_lock(self, mock_region): + database = _Database() + database.spanner_api = self._make_spanner_api() + database.spanner_api.execute_sql.side_effect = RuntimeError() + session = _Session(database) + transaction = self._make_one(session) + self.assertIsNone(transaction._transaction_id) + self.assertFalse(transaction._lock.locked()) + + with pytest.raises(RuntimeError): + await transaction.execute_update(DML_QUERY) + + self.assertFalse(transaction._lock.locked()) + async def _execute_update_helper( self, count=0, @@ -1061,6 +1080,25 @@ async def test_batch_update_other_error(self, mock_region): with pytest.raises(RuntimeError): await transaction.batch_update(statements=[DML_QUERY]) + @mock.patch( + "google.cloud.spanner_v1._opentelemetry_tracing._get_cloud_region", + return_value="global", + ) + @CrossSync.pytest + async def test_batch_update_inline_begin_error_releases_lock(self, mock_region): + database = _Database() + database.spanner_api = self._make_spanner_api() + database.spanner_api.execute_batch_dml.side_effect = RuntimeError() + session = _Session(database) + transaction = self._make_one(session) + self.assertIsNone(transaction._transaction_id) + self.assertFalse(transaction._lock.locked()) + + with pytest.raises(RuntimeError): + await transaction.batch_update(statements=[DML_QUERY]) + + self.assertFalse(transaction._lock.locked()) + async def _batch_update_helper( self, error_after=None, diff --git a/packages/google-cloud-spanner/tests/unit/omni/test_credentials.py b/packages/google-cloud-spanner/tests/unit/omni/test_credentials.py new file mode 100644 index 000000000000..9ca506350169 --- /dev/null +++ b/packages/google-cloud-spanner/tests/unit/omni/test_credentials.py @@ -0,0 +1,559 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import base64 +import datetime +import unittest +from collections import namedtuple +from unittest import mock + +import google.auth.exceptions +import grpc +from google.protobuf import timestamp_pb2 + +from google.cloud.spanner_v1.omni.credentials import SpannerOmniCredentials +from google.cloud.spanner_v1.omni.proto import login_pb2 + + +class TestSpannerOmniCredentials(unittest.TestCase): + def test_init_validation(self): + with self.assertRaises(ValueError): + SpannerOmniCredentials("", "password", "localhost:9010") + with self.assertRaises(ValueError): + SpannerOmniCredentials("user", "", "localhost:9010") + with self.assertRaises(ValueError): + SpannerOmniCredentials("user", "password", "") + + def test_target_scheme_parsing(self): + creds_http = SpannerOmniCredentials("user", "pass", "http://localhost:9010") + self.assertEqual(creds_http.target, "localhost:9010") + self.assertTrue(creds_http.use_plain_text) + + creds_https = SpannerOmniCredentials("user", "pass", "https://localhost:9010") + self.assertEqual(creds_https.target, "localhost:9010") + self.assertFalse(creds_https.use_plain_text) + + creds_raw = SpannerOmniCredentials( + "user", "pass", "localhost:9010", use_plain_text=True + ) + self.assertEqual(creds_raw.target, "localhost:9010") + self.assertTrue(creds_raw.use_plain_text) + + def test_refresh_success(self): + creds = SpannerOmniCredentials( + "user", "pass", "localhost:9010", ca_certificate="/dummy/ca.pem" + ) + + mock_token_proto = login_pb2.AccessToken( + username="user", + expiration_time=timestamp_pb2.Timestamp(seconds=1700000000, nanos=0), + signature=b"test_sig", + key_id=42, + ) + + with ( + mock.patch("builtins.open", mock.mock_open(read_data=b"dummy_ca")), + mock.patch("grpc.secure_channel") as mock_sec_channel, + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.return_value = mock_token_proto + + creds.refresh() + + self.assertIsNotNone(creds.token) + # Verify base64 token decodes back to proto + decoded_bytes = base64.b64decode(creds.token) + parsed_token = login_pb2.AccessToken.FromString(decoded_bytes) + self.assertEqual(parsed_token.username, "user") + self.assertEqual(parsed_token.signature, b"test_sig") + self.assertEqual(parsed_token.key_id, 42) + self.assertEqual( + creds.expiry, + datetime.datetime.fromtimestamp( + 1700000000, tz=datetime.timezone.utc + ).replace(tzinfo=None), + ) + mock_sec_channel.return_value.close.assert_called_once() + + def test_refresh_plaintext_channel(self): + creds = SpannerOmniCredentials("user", "pass", "http://localhost:9010") + mock_token_proto = login_pb2.AccessToken(username="user") + + with ( + mock.patch("grpc.insecure_channel") as mock_insec_channel, + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.return_value = mock_token_proto + + creds.refresh() + + mock_insec_channel.assert_called_once_with("localhost:9010") + mock_insec_channel.return_value.close.assert_called_once() + self.assertIsNotNone(creds.token) + + def test_refresh_missing_ca_certificate_raises(self): + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + with self.assertRaises(google.auth.exceptions.RefreshError) as cm: + creds.refresh() + self.assertIn("requires ca_certificate to be set", str(cm.exception)) + + def test_refresh_mtls_success(self): + creds = SpannerOmniCredentials( + "user", + "pass", + "localhost:9010", + ca_certificate="/dummy/ca.pem", + client_certificate="/dummy/cert.pem", + client_key="/dummy/key.pem", + ) + mock_token_proto = login_pb2.AccessToken(username="user") + + with ( + mock.patch("builtins.open", mock.mock_open(read_data=b"dummy_data")), + mock.patch("grpc.ssl_channel_credentials") as mock_ssl_creds, + mock.patch("grpc.secure_channel") as mock_sec_channel, + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.return_value = mock_token_proto + + creds.refresh() + + mock_ssl_creds.assert_called_once_with( + root_certificates=b"dummy_data", + private_key=b"dummy_data", + certificate_chain=b"dummy_data", + ) + mock_sec_channel.assert_called_once_with( + "localhost:9010", mock_ssl_creds.return_value + ) + self.assertIsNotNone(creds.token) + + def test_refresh_zero_expiration_time_falls_back_to_default_ttl(self): + creds = SpannerOmniCredentials( + "user", "pass", "localhost:9010", use_plain_text=True + ) + mock_token_proto = login_pb2.AccessToken(username="user") + mock_token_proto.expiration_time.seconds = 0 + mock_token_proto.expiration_time.nanos = 0 + + with ( + mock.patch("grpc.insecure_channel"), + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.return_value = mock_token_proto + + creds.refresh() + + self.assertIsNotNone(creds.token) + self.assertTrue(creds.valid) + now = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None) + self.assertGreater(creds.expiry, now + datetime.timedelta(minutes=50)) + + def test_refresh_nanos_only_expiration_time(self): + creds = SpannerOmniCredentials( + "user", "pass", "localhost:9010", use_plain_text=True + ) + now_ts = datetime.datetime.now(datetime.timezone.utc).timestamp() + mock_token_proto = login_pb2.AccessToken(username="user") + mock_token_proto.expiration_time.seconds = int(now_ts) + 300 + mock_token_proto.expiration_time.nanos = 500000 + + with ( + mock.patch("grpc.insecure_channel"), + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.return_value = mock_token_proto + + creds.refresh() + + self.assertIsNotNone(creds.token) + self.assertTrue(creds.valid) + now = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None) + self.assertGreater(creds.expiry, now + datetime.timedelta(minutes=4)) + + def test_refresh_mtls_missing_key_raises(self): + creds = SpannerOmniCredentials( + "user", + "pass", + "localhost:9010", + ca_certificate="/dummy/ca.pem", + client_certificate="/dummy/cert.pem", + ) + with ( + mock.patch("builtins.open", mock.mock_open(read_data=b"dummy_data")), + self.assertRaises(google.auth.exceptions.RefreshError) as cm, + ): + creds.refresh() + self.assertIn( + "Both client_certificate and client_key must be provided", + str(cm.exception), + ) + + def test_refresh_failure_wraps_in_refresh_error(self): + creds = SpannerOmniCredentials( + "user", "pass", "localhost:9010", ca_certificate="/dummy/ca.pem" + ) + + with ( + mock.patch("builtins.open", mock.mock_open(read_data=b"dummy_data")), + mock.patch("grpc.secure_channel"), + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.side_effect = ValueError("Handshake failed") + + with self.assertRaises(google.auth.exceptions.RefreshError): + creds.refresh() + + def test_refresh_grpc_error_is_reraised(self): + creds = SpannerOmniCredentials( + "user", "pass", "localhost:9010", ca_certificate="/dummy/ca.pem" + ) + + class CustomRpcError(grpc.RpcError): + pass + + with ( + mock.patch("builtins.open", mock.mock_open(read_data=b"dummy_data")), + mock.patch("grpc.secure_channel"), + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.side_effect = CustomRpcError("Service Unavailable") + + with self.assertRaises(CustomRpcError): + creds.refresh() + + def test_refresh_skips_when_valid_inside_lock(self): + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + creds.token = "existing_valid_token" + creds.expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + + with mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls: + creds.refresh() + mock_login_client_cls.assert_not_called() + + def test_apply_and_before_request(self): + creds = SpannerOmniCredentials( + "user", "pass", "localhost:9010", ca_certificate="/dummy/ca.pem" + ) + headers = {} + + mock_token_proto = login_pb2.AccessToken(username="user") + with ( + mock.patch("builtins.open", mock.mock_open(read_data=b"dummy_data")), + mock.patch("grpc.secure_channel"), + mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls, + ): + mock_client = mock_login_client_cls.return_value + mock_client.login.return_value = mock_token_proto + + creds.before_request(None, "POST", "http://localhost", headers) + + self.assertIn("authorization", headers) + self.assertTrue(headers["authorization"].startswith("Bearer ")) + + def test_interceptor(self): + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + creds.token = "sample_test_token" + creds.expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + + interceptor = creds.create_auth_interceptor() + + DummyCallDetails = namedtuple( + "DummyCallDetails", + ["method", "timeout", "metadata", "credentials", "wait_for_ready"], + ) + call_details = DummyCallDetails( + method="/google.spanner.v1.Spanner/ExecuteSql", + timeout=30.0, + metadata=[("custom-header", "custom-val")], + credentials=None, + wait_for_ready=None, + ) + + def dummy_continuation(details, req): + return details + + # Unary-Unary + res = interceptor.intercept_unary_unary(dummy_continuation, call_details, "req") + self.assertIn(("authorization", "Bearer sample_test_token"), res.metadata) + self.assertIn(("custom-header", "custom-val"), res.metadata) + + # Unary-Stream + res_us = interceptor.intercept_unary_stream( + dummy_continuation, call_details, "req" + ) + self.assertIn(("authorization", "Bearer sample_test_token"), res_us.metadata) + + # Stream-Unary + res_su = interceptor.intercept_stream_unary( + dummy_continuation, call_details, ["req"] + ) + self.assertIn(("authorization", "Bearer sample_test_token"), res_su.metadata) + + # Stream-Stream + res_ss = interceptor.intercept_stream_stream( + dummy_continuation, call_details, ["req"] + ) + self.assertIn(("authorization", "Bearer sample_test_token"), res_ss.metadata) + + def test_async_interceptor_attaches_bearer_token(self): + import asyncio + + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + creds.token = "async_test_token" + creds.expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + + interceptors = creds.create_async_auth_interceptors() + self.assertEqual(len(interceptors), 4) + + DummyCallDetails = namedtuple( + "DummyCallDetails", + ["method", "timeout", "metadata", "credentials", "wait_for_ready"], + ) + call_details = DummyCallDetails( + method="/google.spanner.v1.Spanner/StreamingRead", + timeout=30.0, + metadata=[("custom-header", "custom-val")], + credentials=None, + wait_for_ready=None, + ) + + async def dummy_async_continuation(details, req): + return details + + async def run_async_tests(): + # Unary-Unary + res_uu = await interceptors[0].intercept_unary_unary( + dummy_async_continuation, call_details, "req" + ) + self.assertIn(("authorization", "Bearer async_test_token"), res_uu.metadata) + self.assertIn(("custom-header", "custom-val"), res_uu.metadata) + + # Unary-Stream + res_us = await interceptors[1].intercept_unary_stream( + dummy_async_continuation, call_details, "req" + ) + self.assertIn(("authorization", "Bearer async_test_token"), res_us.metadata) + + # Stream-Unary + res_su = await interceptors[2].intercept_stream_unary( + dummy_async_continuation, call_details, ["req"] + ) + self.assertIn(("authorization", "Bearer async_test_token"), res_su.metadata) + + # Stream-Stream + res_ss = await interceptors[3].intercept_stream_stream( + dummy_async_continuation, call_details, ["req"] + ) + self.assertIn(("authorization", "Bearer async_test_token"), res_ss.metadata) + + asyncio.run(run_async_tests()) + + def test_async_interceptor_triggers_refresh_when_invalid(self): + import asyncio + + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + interceptors = creds.create_async_auth_interceptors() + + DummyCallDetails = namedtuple( + "DummyCallDetails", + ["method", "timeout", "metadata", "credentials", "wait_for_ready"], + ) + call_details = DummyCallDetails( + method="/google.spanner.v1.Spanner/ExecuteSql", + timeout=30.0, + metadata=[], + credentials=None, + wait_for_ready=None, + ) + + async def dummy_async_continuation(details, req): + return details + + async def run_test(): + with mock.patch.object(creds, "refresh") as mock_refresh: + + def do_refresh(): + creds.token = "refreshed_async_token" + creds.expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + + mock_refresh.side_effect = do_refresh + + res = await interceptors[0].intercept_unary_unary( + dummy_async_continuation, call_details, "req" + ) + mock_refresh.assert_called_once() + self.assertIn( + ("authorization", "Bearer refreshed_async_token"), res.metadata + ) + + asyncio.run(run_test()) + + def test_init_channel(self): + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + mock_ssl = mock.Mock(spec=grpc.ChannelCredentials) + creds.init_channel( + use_plain_text=True, + ca_certificate="ca.pem", + client_certificate="client.pem", + client_key="key.pem", + ssl_credentials=mock_ssl, + ) + self.assertTrue(creds.use_plain_text) + self.assertEqual(creds.ca_certificate, "ca.pem") + self.assertEqual(creds.client_certificate, "client.pem") + self.assertEqual(creds.client_key, "key.pem") + self.assertIs(creds.ssl_credentials, mock_ssl) + + # Also test with use_plain_text=False + creds.init_channel(use_plain_text=False) + self.assertFalse(creds.use_plain_text) + + def test_create_auth_interceptor_async_dispatch(self): + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + interceptors = creds.create_auth_interceptor(is_async=True) + self.assertIsInstance(interceptors, list) + self.assertEqual(len(interceptors), 4) + + interceptors_alias = creds.create_async_auth_interceptor() + self.assertIsInstance(interceptors_alias, list) + self.assertEqual(len(interceptors_alias), 4) + + def test_sync_interceptor_triggers_refresh_when_invalid(self): + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + interceptor = creds.create_auth_interceptor() + + DummyCallDetails = namedtuple( + "DummyCallDetails", + ["method", "timeout", "metadata", "credentials", "wait_for_ready"], + ) + call_details = DummyCallDetails( + method="/google.spanner.v1.Spanner/ExecuteSql", + timeout=30.0, + metadata=[], + credentials=None, + wait_for_ready=None, + ) + + def dummy_continuation(details, req): + return details + + with mock.patch.object(creds, "refresh") as mock_refresh: + + def do_refresh(): + creds.token = "refreshed_sync_token" + creds.expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + + mock_refresh.side_effect = do_refresh + + res = interceptor.intercept_unary_unary( + dummy_continuation, call_details, "req" + ) + mock_refresh.assert_called_once() + self.assertIn( + ("authorization", "Bearer refreshed_sync_token"), res.metadata + ) + + def test_perform_refresh_token_with_ssl_credentials(self): + mock_ssl = mock.Mock(spec=grpc.ChannelCredentials) + creds = SpannerOmniCredentials( + "user", + "pass", + "localhost:9010", + ssl_credentials=mock_ssl, + ) + with mock.patch("grpc.secure_channel") as mock_secure_channel: + mock_channel = mock.MagicMock() + mock_secure_channel.return_value = mock_channel + with mock.patch( + "google.cloud.spanner_v1.omni.credentials.LoginClient" + ) as mock_login_client_cls: + mock_client = mock.MagicMock() + mock_login_client_cls.return_value = mock_client + proto_token = login_pb2.AccessToken( + username="user", signature=b"secure_token" + ) + mock_client.login.return_value = proto_token + + creds.refresh() + + mock_secure_channel.assert_called_once_with("localhost:9010", mock_ssl) + self.assertTrue(creds.valid) + self.assertIsNotNone(creds.token) + mock_channel.close.assert_called_once() + + def test_before_request(self): + creds = SpannerOmniCredentials("user", "pass", "localhost:9010") + headers = {} + + with mock.patch.object(creds, "refresh") as mock_refresh: + + def do_refresh(request=None): + creds.token = "refreshed_token" + creds.expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + + mock_refresh.side_effect = do_refresh + + creds.before_request(None, "GET", "http://example.com", headers) + mock_refresh.assert_called_once() + self.assertEqual(headers["authorization"], "Bearer refreshed_token") + + # Call again when valid - refresh should not be called again + mock_refresh.reset_mock() + headers_2 = {} + creds.before_request(None, "GET", "http://example.com", headers_2) + mock_refresh.assert_not_called() + self.assertEqual(headers_2["authorization"], "Bearer refreshed_token") + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/google-cloud-spanner/tests/unit/omni/test_login_client.py b/packages/google-cloud-spanner/tests/unit/omni/test_login_client.py new file mode 100644 index 000000000000..3d080cd67859 --- /dev/null +++ b/packages/google-cloud-spanner/tests/unit/omni/test_login_client.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest +from unittest import mock + +import grpc +from google.protobuf import timestamp_pb2 + +from google.cloud.spanner_v1.omni import opaque +from google.cloud.spanner_v1.omni.login_client import LoginClient +from google.cloud.spanner_v1.omni.proto import authentication_pb2, login_pb2 + + +class TestLoginClient(unittest.TestCase): + def setUp(self): + self.mock_channel = mock.MagicMock(spec=grpc.Channel) + + def test_login_empty_inputs(self): + client = LoginClient(self.mock_channel) + with self.assertRaises(ValueError): + client.login("", "password") + with self.assertRaises(ValueError): + client.login("user", "") + + def test_login_successful_flow(self): + username = "admin" + password = b"secret123" + + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + + # Precompute server artifacts + oprf_seed = opaque.nonce() + oprf_key_seed = opaque.expand( + oprf_seed, (username + "OprfKey").encode("utf-8"), 32 + ) + _, oprf_priv = opaque.derive_key_pair(oprf_key_seed, b"OPAQUE-DeriveKeyPair") + + h_pt = opaque.hash_to_curve_p256(password, opaque.LOGIN_DOMAIN_SEPARATION_TAG) + prf_pt = opaque.point_mul(h_pt, int.from_bytes(oprf_priv, "big")) + prf = opaque.marshal_compressed(prf_pt) + + stretched_oprf = opaque.stretch(prf, params) + randomized_password = opaque.extract(opaque.concat(prf, stretched_oprf)) + + server_key_seed = opaque.nonce() + server_pub, server_priv = opaque.derive_key_pair( + server_key_seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + + envelope_nonce = opaque.nonce() + auth_key = opaque.expand( + randomized_password, envelope_nonce + opaque.AUTH_KEY_INFO, 32 + ) + auth_tag = opaque.mac( + auth_key, envelope_nonce + server_pub + username.encode("utf-8") + ) + serialized_envelope = opaque.concat(server_pub, envelope_nonce, auth_tag) + + masking_key = opaque.expand(randomized_password, opaque.MASKING_KEY_INFO, 32) + masking_nonce = opaque.nonce() + credential_pad = opaque.expand( + masking_key, + opaque.concat(masking_nonce, b"CredentialResponsePad"), + len(serialized_envelope), + ) + masked_response = opaque.xor_bytes(serialized_envelope, credential_pad) + + expected_access_token = login_pb2.AccessToken( + username=username, + creation_time=timestamp_pb2.Timestamp(seconds=1000, nanos=0), + expiration_time=timestamp_pb2.Timestamp(seconds=4600, nanos=0), + signature=b"valid_signature", + key_id=1, + access_token_type=login_pb2.AccessToken.ACCESS_TOKEN_TYPE_API, + ) + + def mock_login_rpc(request_iterator, timeout=None): + # Step 1: receive handshake request + req1 = next(request_iterator) + self.assertEqual(req1.username, username) + self.assertTrue(req1.HasField("handshake_request")) + + # Return Step 1 response + yield login_pb2.LoginResponse( + handshake_response=authentication_pb2.PasswordAuthenticationHandshakeResponse( + password_authentication_protocol=authentication_pb2.PasswordAuthenticationProtocol.PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE, + hash_parameters=params, + ) + ) + + # Step 2: receive initial opaque request + req2 = next(request_iterator) + init_req = req2.opaque_request.initial_request + blinded_msg = init_req.blinded_message + client_nonce = init_req.client_nonce + client_pub_keyshare = init_req.client_public_keyshare + + blinded_pt = opaque.unmarshal_compressed(blinded_msg) + eval_pt = opaque.point_mul(blinded_pt, int.from_bytes(oprf_priv, "big")) + evaluated_msg = opaque.marshal_compressed(eval_pt) + + server_ephemeral_pub, server_ephemeral_priv = opaque.derive_key_pair( + opaque.nonce(), opaque.DIFFIE_HELLMAN_KEY_INFO + ) + server_login_nonce = opaque.nonce() + + seed = opaque.expand( + randomized_password, envelope_nonce + opaque.PRIVATE_KEY_INFO, 32 + ) + client_pub, _ = opaque.derive_key_pair(seed, opaque.DIFFIE_HELLMAN_KEY_INFO) + + s_dh1 = opaque.diffie_hellman(server_ephemeral_priv, client_pub_keyshare) + s_dh2 = opaque.diffie_hellman(server_priv, client_pub_keyshare) + s_dh3 = opaque.diffie_hellman(server_ephemeral_priv, client_pub) + s_ikm = opaque.concat(s_dh1, s_dh2, s_dh3) + + preamble = opaque.concat( + b"OPAQUEv1-", + username.encode("utf-8"), + client_nonce, + client_pub_keyshare, + server_pub, + evaluated_msg, + server_login_nonce, + server_ephemeral_pub, + ) + + s_km2, _, _ = opaque.derive_shared_keys(s_ikm, preamble) + server_mac = opaque.mac(s_km2, opaque.sha256_hash(preamble)) + + # Return Step 2 response + yield login_pb2.LoginResponse( + opaque_response=login_pb2.OpaqueLoginResponse( + initial_response=login_pb2.InitialOpaqueLoginResponse( + server_nonce=server_login_nonce, + server_public_keyshare=server_ephemeral_pub, + server_mac=server_mac, + evaluated_message=evaluated_msg, + masking_nonce=masking_nonce, + masked_response=masked_response, + ) + ) + ) + + # Step 3: receive final opaque request + req3 = next(request_iterator) + self.assertTrue(req3.opaque_request.HasField("final_request")) + + # Return Step 3 response + yield login_pb2.LoginResponse(access_token=expected_access_token) + + with mock.patch( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc.LoginServiceStub" + ) as mock_stub_cls: + mock_stub = mock_stub_cls.return_value + mock_stub.Login.side_effect = mock_login_rpc + + client = LoginClient(self.mock_channel) + token = client.login(username, password) + + self.assertEqual(token.username, username) + self.assertEqual(token.signature, b"valid_signature") + self.assertEqual(token.key_id, 1) + self.assertEqual(token.expiration_time.seconds, 4600) + + def test_login_unsupported_protocol(self): + def mock_login_rpc(request_iterator, timeout=None): + next(request_iterator) + yield login_pb2.LoginResponse( + handshake_response=authentication_pb2.PasswordAuthenticationHandshakeResponse( + password_authentication_protocol=authentication_pb2.PasswordAuthenticationProtocol.PASSWORD_AUTHENTICATION_PROTOCOL_UNSPECIFIED, + ) + ) + + with mock.patch( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc.LoginServiceStub" + ) as mock_stub_cls: + mock_stub = mock_stub_cls.return_value + mock_stub.Login.side_effect = mock_login_rpc + + client = LoginClient(self.mock_channel) + with self.assertRaises(ValueError) as cm: + client.login("user", "pass") + self.assertIn( + "Unsupported password authentication protocol", str(cm.exception) + ) + + def test_login_missing_handshake_response(self): + def mock_login_rpc(request_iterator, timeout=None): + next(request_iterator) + yield login_pb2.LoginResponse() + + with mock.patch( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc.LoginServiceStub" + ) as mock_stub_cls: + mock_stub = mock_stub_cls.return_value + mock_stub.Login.side_effect = mock_login_rpc + + client = LoginClient(self.mock_channel) + with self.assertRaises(ValueError) as cm: + client.login("user", "pass") + self.assertIn("Failed to receive handshake response", str(cm.exception)) + + def test_login_missing_hash_parameters(self): + def mock_login_rpc(request_iterator, timeout=None): + next(request_iterator) + yield login_pb2.LoginResponse( + handshake_response=authentication_pb2.PasswordAuthenticationHandshakeResponse( + password_authentication_protocol=authentication_pb2.PasswordAuthenticationProtocol.PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE, + ) + ) + + with mock.patch( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc.LoginServiceStub" + ) as mock_stub_cls: + mock_stub = mock_stub_cls.return_value + mock_stub.Login.side_effect = mock_login_rpc + + client = LoginClient(self.mock_channel) + with self.assertRaises(ValueError) as cm: + client.login("user", "pass") + self.assertIn( + "Handshake response missing hash_parameters", str(cm.exception) + ) + + def test_login_missing_access_token_in_final_response(self): + username = "test_user" + password = "test_password" + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + + oprf_seed = opaque.nonce() + oprf_key_seed = opaque.expand( + oprf_seed, (username + "OprfKey").encode("utf-8"), 32 + ) + _, oprf_priv = opaque.derive_key_pair(oprf_key_seed, b"OPAQUE-DeriveKeyPair") + h_pt = opaque.hash_to_curve_p256( + password.encode("utf-8"), opaque.LOGIN_DOMAIN_SEPARATION_TAG + ) + prf_pt = opaque.point_mul(h_pt, int.from_bytes(oprf_priv, "big")) + prf = opaque.marshal_compressed(prf_pt) + stretched_oprf = opaque.stretch(prf, params) + randomized_password = opaque.extract(opaque.concat(prf, stretched_oprf)) + + server_key_seed = opaque.nonce() + server_pub, server_priv = opaque.derive_key_pair( + server_key_seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + envelope_nonce = opaque.nonce() + auth_key = opaque.expand( + randomized_password, envelope_nonce + opaque.AUTH_KEY_INFO, 32 + ) + auth_tag = opaque.mac( + auth_key, envelope_nonce + server_pub + username.encode("utf-8") + ) + serialized_envelope = opaque.concat(server_pub, envelope_nonce, auth_tag) + masking_key = opaque.expand(randomized_password, opaque.MASKING_KEY_INFO, 32) + masking_nonce = opaque.nonce() + credential_pad = opaque.expand( + masking_key, + opaque.concat(masking_nonce, b"CredentialResponsePad"), + len(serialized_envelope), + ) + masked_response = opaque.xor_bytes(serialized_envelope, credential_pad) + + def mock_login_rpc(request_iterator, timeout=None): + next(request_iterator) + yield login_pb2.LoginResponse( + handshake_response=authentication_pb2.PasswordAuthenticationHandshakeResponse( + password_authentication_protocol=authentication_pb2.PasswordAuthenticationProtocol.PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE, + hash_parameters=params, + ) + ) + + req2 = next(request_iterator) + init_req = req2.opaque_request.initial_request + blinded_msg = init_req.blinded_message + client_nonce = init_req.client_nonce + client_pub_keyshare = init_req.client_public_keyshare + + blinded_pt = opaque.unmarshal_compressed(blinded_msg) + eval_pt = opaque.point_mul(blinded_pt, int.from_bytes(oprf_priv, "big")) + evaluated_msg = opaque.marshal_compressed(eval_pt) + + server_ephemeral_pub, server_ephemeral_priv = opaque.derive_key_pair( + opaque.nonce(), opaque.DIFFIE_HELLMAN_KEY_INFO + ) + server_login_nonce = opaque.nonce() + seed = opaque.expand( + randomized_password, envelope_nonce + opaque.PRIVATE_KEY_INFO, 32 + ) + client_pub, _ = opaque.derive_key_pair(seed, opaque.DIFFIE_HELLMAN_KEY_INFO) + + s_dh1 = opaque.diffie_hellman(server_ephemeral_priv, client_pub_keyshare) + s_dh2 = opaque.diffie_hellman(server_priv, client_pub_keyshare) + s_dh3 = opaque.diffie_hellman(server_ephemeral_priv, client_pub) + s_ikm = opaque.concat(s_dh1, s_dh2, s_dh3) + + preamble = opaque.concat( + b"OPAQUEv1-", + username.encode("utf-8"), + client_nonce, + client_pub_keyshare, + server_pub, + evaluated_msg, + server_login_nonce, + server_ephemeral_pub, + ) + s_km2, _, _ = opaque.derive_shared_keys(s_ikm, preamble) + server_mac = opaque.mac(s_km2, opaque.sha256_hash(preamble)) + + yield login_pb2.LoginResponse( + opaque_response=login_pb2.OpaqueLoginResponse( + initial_response=login_pb2.InitialOpaqueLoginResponse( + server_nonce=server_login_nonce, + server_public_keyshare=server_ephemeral_pub, + server_mac=server_mac, + evaluated_message=evaluated_msg, + masking_nonce=masking_nonce, + masked_response=masked_response, + ) + ) + ) + + next(request_iterator) + # Response without access_token + yield login_pb2.LoginResponse() + + with mock.patch( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc.LoginServiceStub" + ) as mock_stub_cls: + mock_stub = mock_stub_cls.return_value + mock_stub.Login.side_effect = mock_login_rpc + + client = LoginClient(self.mock_channel) + with self.assertRaises(ValueError) as cm: + client.login(username, password) + self.assertIn( + "Server failed to return an access token in final response", + str(cm.exception), + ) + + def test_request_iterator_iter_and_stop(self): + from google.cloud.spanner_v1.omni.login_client import _RequestIterator + + req_iterator = _RequestIterator() + self.assertIs(iter(req_iterator), req_iterator) + + req = login_pb2.LoginRequest(username="u") + req_iterator.send(req) + self.assertEqual(next(req_iterator), req) + + req_iterator.close() + with self.assertRaises(StopIteration): + next(req_iterator) + + def test_request_iterator_close_idempotent(self): + from google.cloud.spanner_v1.omni.login_client import _RequestIterator + + req_iterator = _RequestIterator() + req_iterator.close() + req_iterator.close() + self.assertEqual(req_iterator._queue.qsize(), 1) + self.assertIsNone(req_iterator._queue.get()) + self.assertTrue(req_iterator._queue.empty()) + + def test_login_exception_cancels_call(self): + mock_call = mock.MagicMock() + mock_call.__next__.side_effect = RuntimeError("network error") + + with mock.patch( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc.LoginServiceStub" + ) as mock_stub_cls: + mock_stub = mock_stub_cls.return_value + mock_stub.Login.return_value = mock_call + + client = LoginClient(self.mock_channel) + with self.assertRaises(RuntimeError): + client.login("user", "pass") + + mock_call.cancel.assert_called_once() + + def test_login_premature_stream_closure(self): + mock_call = mock.MagicMock() + mock_call.__next__.side_effect = StopIteration + + with mock.patch( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc.LoginServiceStub" + ) as mock_stub_cls: + mock_stub = mock_stub_cls.return_value + mock_stub.Login.return_value = mock_call + + client = LoginClient(self.mock_channel) + with self.assertRaises(ValueError) as cm: + client.login("user", "pass") + self.assertIn( + "Server closed stream prematurely during handshake", str(cm.exception) + ) + + def test_grpc_servicers_and_helpers(self): + import grpc + + from google.cloud.spanner_v1.omni.proto import login_pb2_grpc + + servicer = login_pb2_grpc.LoginServiceServicer() + mock_context = mock.MagicMock() + with self.assertRaises(NotImplementedError): + servicer.Login(iter([]), mock_context) + mock_context.set_code.assert_called_once_with(grpc.StatusCode.UNIMPLEMENTED) + mock_context.set_details.assert_called_once_with("Method not implemented!") + + mock_server = mock.MagicMock() + login_pb2_grpc.add_LoginServiceServicer_to_server(servicer, mock_server) + mock_server.add_generic_rpc_handlers.assert_called_once() + mock_server.add_registered_method_handlers.assert_called_once() + + with mock.patch("grpc.experimental.stream_stream") as mock_ss: + login_pb2_grpc.LoginService.Login(iter([]), "target_host") + mock_ss.assert_called_once() + + def test_grpc_version_mismatch_paths(self): + import importlib + + try: + importlib.import_module("grpc._utilities") + except ImportError: + pass + + # Test login_pb2_grpc version mismatch check + with mock.patch( + "grpc._utilities.first_version_is_lower", create=True, return_value=True + ): + with self.assertRaises(RuntimeError) as cm: + importlib.reload( + importlib.import_module( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc" + ) + ) + self.assertIn("The grpc package installed is at version", str(cm.exception)) + + with mock.patch( + "grpc._utilities.first_version_is_lower", create=True, return_value=True + ): + with self.assertRaises(RuntimeError) as cm: + importlib.reload( + importlib.import_module( + "google.cloud.spanner_v1.omni.proto.authentication_pb2_grpc" + ) + ) + self.assertIn("The grpc package installed is at version", str(cm.exception)) + + # Test ImportError fallback when first_version_is_lower cannot be imported + import sys + + orig_utilities = sys.modules.get("grpc._utilities") + try: + sys.modules["grpc._utilities"] = None + importlib.reload( + importlib.import_module( + "google.cloud.spanner_v1.omni.proto.login_pb2_grpc" + ) + ) + importlib.reload( + importlib.import_module( + "google.cloud.spanner_v1.omni.proto.authentication_pb2_grpc" + ) + ) + finally: + if orig_utilities is not None: + sys.modules["grpc._utilities"] = orig_utilities + else: + sys.modules.pop("grpc._utilities", None) + + # Restore modules to standard state + importlib.reload( + importlib.import_module("google.cloud.spanner_v1.omni.proto.login_pb2_grpc") + ) + importlib.reload( + importlib.import_module( + "google.cloud.spanner_v1.omni.proto.authentication_pb2_grpc" + ) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/google-cloud-spanner/tests/unit/omni/test_opaque.py b/packages/google-cloud-spanner/tests/unit/omni/test_opaque.py new file mode 100644 index 000000000000..e2816ff0c22a --- /dev/null +++ b/packages/google-cloud-spanner/tests/unit/omni/test_opaque.py @@ -0,0 +1,1108 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest +from unittest import mock + +from google.cloud.spanner_v1.omni import opaque +from google.cloud.spanner_v1.omni.proto import authentication_pb2, login_pb2 + + +class TestOpaqueCrypto(unittest.TestCase): + def test_random_oracle_sha256(self): + max_val = 1 << 63 + test_inputs = [b"key", b"key2", bytes([97, 97, 98, 99, 100, 101])] + for inp in test_inputs: + expected = opaque.random_oracle_sha256(inp, max_val) + self.assertEqual(len(expected), 32) + for _ in range(10): + out = opaque.random_oracle_sha256(inp, max_val) + self.assertEqual(out, expected) + + def test_random_oracle_sha256_large_domain_raises(self): + max_val = 1 << 65500 + with self.assertRaises(ValueError) as cm: + opaque.random_oracle_sha256(b"key", max_val) + self.assertIn( + "Domain bit length must not be greater than 65280", str(cm.exception) + ) + + def test_mac(self): + tests = [ + (b"key", b"data"), + (b"key", b"data2"), + ( + bytes([97, 97, 98, 99, 100, 101]), + bytes([102, 103, 104, 105, 106, 107]), + ), + ] + for k, d in tests: + m1 = opaque.mac(k, d) + m2 = opaque.mac(k, d) + self.assertEqual(m1, m2) + self.assertEqual(len(m1), 32) + + def test_xor_bytes(self): + tests = [ + (b"abc", b"def", False), + ( + bytes([97, 97, 98, 99, 100, 101]), + bytes([102, 103, 104, 105, 106, 107]), + False, + ), + ( + bytes([97, 97, 98, 99, 100, 101]), + bytes([0, 0, 0, 0, 0, 0]), + False, + ), + (b"abc", b"defghi", True), + (b"abcdefghi", b"jklmnop", True), + (b"", b"", False), + ] + for a, b, want_err in tests: + if want_err: + with self.assertRaises(ValueError): + opaque.xor_bytes(a, b) + else: + xored = opaque.xor_bytes(a, b) + self.assertEqual(len(xored), len(a)) + orig = opaque.xor_bytes(xored, b) + self.assertEqual(orig, a) + + def test_stretch(self): + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=5, + memory_usage=7 * 1024, + parallelism=1, + hash_size=32, + ) + ) + long_input = bytes(range(256)) * 4 + + tests = [ + ( + b"", + bytes( + [ + 58, + 42, + 135, + 162, + 54, + 231, + 153, + 103, + 111, + 241, + 220, + 39, + 245, + 158, + 231, + 5, + 157, + 108, + 133, + 178, + 37, + 97, + 185, + 220, + 104, + 13, + 66, + 147, + 221, + 19, + 198, + 9, + ] + ), + ), + ( + b"input", + bytes( + [ + 177, + 173, + 204, + 142, + 245, + 214, + 91, + 164, + 139, + 85, + 150, + 101, + 204, + 187, + 48, + 176, + 251, + 7, + 154, + 247, + 251, + 35, + 241, + 135, + 99, + 117, + 14, + 121, + 182, + 124, + 87, + 46, + ] + ), + ), + ( + bytes([97, 97, 98, 99, 100, 101]), + bytes( + [ + 164, + 94, + 8, + 109, + 17, + 19, + 42, + 55, + 86, + 44, + 54, + 89, + 255, + 148, + 130, + 248, + 133, + 4, + 40, + 24, + 246, + 27, + 81, + 56, + 231, + 137, + 238, + 30, + 67, + 159, + 3, + 157, + ] + ), + ), + ( + long_input, + bytes( + [ + 132, + 52, + 182, + 135, + 97, + 18, + 8, + 254, + 10, + 1, + 94, + 98, + 78, + 193, + 246, + 160, + 12, + 209, + 142, + 253, + 247, + 115, + 4, + 149, + 141, + 2, + 105, + 159, + 139, + 94, + 161, + 116, + ] + ), + ), + ] + for inp, expected in tests: + stretched = opaque.stretch(inp, params) + self.assertEqual(len(stretched), 32) + self.assertEqual(stretched, expected) + + def test_extract(self): + long_input = bytes(range(256)) * 4 + tests = [ + ( + b"", + bytes( + [ + 99, + 252, + 241, + 111, + 84, + 209, + 178, + 181, + 88, + 96, + 91, + 194, + 149, + 79, + 240, + 143, + 252, + 68, + 135, + 177, + 69, + 144, + 33, + 115, + 195, + 224, + 100, + 31, + 46, + 160, + 150, + 41, + ] + ), + ), + ( + b"input", + bytes( + [ + 94, + 113, + 123, + 114, + 170, + 250, + 213, + 241, + 247, + 203, + 160, + 141, + 111, + 233, + 68, + 240, + 123, + 33, + 207, + 139, + 115, + 44, + 249, + 217, + 77, + 34, + 6, + 254, + 77, + 75, + 20, + 99, + ] + ), + ), + ( + bytes([97, 97, 98, 99, 100, 101]), + bytes( + [ + 48, + 112, + 244, + 9, + 53, + 2, + 10, + 147, + 218, + 132, + 43, + 198, + 200, + 101, + 20, + 3, + 71, + 158, + 227, + 3, + 161, + 15, + 215, + 112, + 251, + 195, + 187, + 96, + 11, + 203, + 226, + 210, + ] + ), + ), + ( + long_input, + bytes( + [ + 246, + 148, + 220, + 16, + 96, + 62, + 53, + 189, + 96, + 83, + 146, + 84, + 233, + 183, + 89, + 12, + 235, + 31, + 24, + 113, + 148, + 25, + 213, + 33, + 167, + 78, + 147, + 162, + 223, + 115, + 38, + 117, + ] + ), + ), + ] + for inp, expected in tests: + extracted = opaque.extract(inp) + self.assertEqual(len(extracted), 32) + self.assertEqual(extracted, expected) + + def test_derive_key_pair(self): + tests = [ + (b"seed", b"info", b"seed", b"info", False), + (b"seed2", b"info", b"seed2", b"info", False), + (b"seed", b"info2", b"seed", b"info2", False), + (b"seed", b"info2", b"different", b"info2", True), + (b"seed", b"info2", b"seed", b"info1", True), + ] + for s1, i1, s2, i2, want_diff in tests: + pub1, priv1 = opaque.derive_key_pair(s1, i1) + pub2, priv2 = opaque.derive_key_pair(s2, i2) + self.assertEqual(len(pub1), 33) + self.assertEqual(len(priv1), 32) + if want_diff: + self.assertNotEqual(priv1, priv2) + self.assertNotEqual(pub1, pub2) + else: + self.assertEqual(priv1, priv2) + self.assertEqual(pub1, pub2) + + def test_diffie_hellman(self): + tests = [ + (b"", b""), + (b"server-seed", b"client-seed"), + (b"server-seed2", b"client-seed2"), + (b"no-need-to-be-the-same-length", b"im-a-shorter-seed"), + ] + for server_seed, client_seed in tests: + server_pub, server_priv = opaque.derive_key_pair( + server_seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + client_pub, client_priv = opaque.derive_key_pair( + client_seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + + server_shared = opaque.diffie_hellman(server_priv, client_pub) + client_shared = opaque.diffie_hellman(client_priv, server_pub) + self.assertEqual(server_shared, client_shared) + + def test_oprf_evaluate(self): + username = "username" + password = b"password1234" + oprf_seed = opaque.nonce() + seed = opaque.expand(oprf_seed, (username + "OprfKey").encode("utf-8"), 32) + _, server_priv = opaque.derive_key_pair(seed, b"OPAQUE-DeriveKeyPair") + + blinded_element, blind_scalar = opaque.blind(password) + + # Server blind evaluation + blinded_pt = opaque.unmarshal_compressed(blinded_element) + evaluated_pt = opaque.point_mul(blinded_pt, int.from_bytes(server_priv, "big")) + evaluated_element = opaque.marshal_compressed(evaluated_pt) + + # Client finalization + oprf = opaque.finalize(blind_scalar, evaluated_element) + + # Direct evaluation + h_pt = opaque.hash_to_curve_p256(password, opaque.LOGIN_DOMAIN_SEPARATION_TAG) + prf_pt = opaque.point_mul(h_pt, int.from_bytes(server_priv, "big")) + prf = opaque.marshal_compressed(prf_pt) + + self.assertEqual(oprf, prf) + + def test_authenticator_validation(self): + valid_params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + + with self.assertRaises(ValueError): + opaque.UserAuthenticator("", b"pass", valid_params) + + with self.assertRaises(ValueError): + opaque.UserAuthenticator("user", b"", valid_params) + + with self.assertRaises(ValueError): + opaque.UserAuthenticator("user", b"pass", None) + + with self.assertRaises(ValueError): + opaque.UserAuthenticator( + "user", + b"pass", + authentication_pb2.HashParameters(), + ).initial_request() + + def test_authenticator_state_errors(self): + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + auth = opaque.UserAuthenticator("user", "password", params) + + # Final before initial + resp = login_pb2.LoginResponse( + opaque_response=login_pb2.OpaqueLoginResponse( + initial_response=login_pb2.InitialOpaqueLoginResponse() + ) + ) + with self.assertRaises(ValueError): + auth.final_request(resp) + + # First initial works + req1 = auth.initial_request() + self.assertEqual(req1.username, "user") + self.assertTrue(req1.opaque_request.HasField("initial_request")) + + # Second initial fails + with self.assertRaises(ValueError): + auth.initial_request() + + def test_user_authenticator_clear_and_del(self): + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + auth = opaque.UserAuthenticator("user", "password", params) + auth.initial_request() + + pw_ref = auth._password + blind_ref = auth._blind + priv_keyshare_ref = auth._client_private_keyshare + + # Test clear() zeroizes buffers and sets them to None + auth.clear() + self.assertIsNone(auth._password) + self.assertIsNone(auth._blind) + self.assertIsNone(auth._client_private_keyshare) + if pw_ref is not None: + self.assertEqual(pw_ref, bytearray(len(pw_ref))) + if blind_ref is not None: + self.assertEqual(blind_ref, bytearray(len(blind_ref))) + if priv_keyshare_ref is not None: + self.assertEqual(priv_keyshare_ref, bytearray(len(priv_keyshare_ref))) + + # Calling clear again is safe + auth.clear() + + # Test __del__ calls clear + auth2 = opaque.UserAuthenticator("user", "password", params) + auth2.initial_request() + pw_ref2 = auth2._password + auth2.__del__() + self.assertIsNone(auth2._password) + if pw_ref2 is not None: + self.assertEqual(pw_ref2, bytearray(len(pw_ref2))) + + def test_full_opaque_handshake_simulation(self): + username = "alice" + password = b"secret_password_123" + + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + + # 1. Server setup user registration: + # oprf_key + oprf_seed = opaque.nonce() + oprf_key_seed = opaque.expand( + oprf_seed, (username + "OprfKey").encode("utf-8"), 32 + ) + _, oprf_priv = opaque.derive_key_pair(oprf_key_seed, b"OPAQUE-DeriveKeyPair") + + # Direct prf for enrollment + h_pt = opaque.hash_to_curve_p256(password, opaque.LOGIN_DOMAIN_SEPARATION_TAG) + prf_pt = opaque.point_mul(h_pt, int.from_bytes(oprf_priv, "big")) + prf = opaque.marshal_compressed(prf_pt) + + stretched_oprf = opaque.stretch(prf, params) + randomized_password = opaque.extract(opaque.concat(prf, stretched_oprf)) + + # Server keypair + server_key_seed = opaque.nonce() + server_pub, server_priv = opaque.derive_key_pair( + server_key_seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + + # Client keypair & envelope + envelope_nonce = opaque.nonce() + auth_key = opaque.expand( + randomized_password, envelope_nonce + opaque.AUTH_KEY_INFO, 32 + ) + auth_tag = opaque.mac( + auth_key, envelope_nonce + server_pub + username.encode("utf-8") + ) + serialized_envelope = opaque.concat(server_pub, envelope_nonce, auth_tag) + + masking_key = opaque.expand(randomized_password, opaque.MASKING_KEY_INFO, 32) + masking_nonce = opaque.nonce() + credential_pad = opaque.expand( + masking_key, + opaque.concat(masking_nonce, b"CredentialResponsePad"), + len(serialized_envelope), + ) + masked_response = opaque.xor_bytes(serialized_envelope, credential_pad) + + # 2. Client starts login + client_auth = opaque.UserAuthenticator(username, password, params) + client_req1 = client_auth.initial_request() + + blinded_msg = client_req1.opaque_request.initial_request.blinded_message + client_nonce = client_req1.opaque_request.initial_request.client_nonce + client_pub_keyshare = ( + client_req1.opaque_request.initial_request.client_public_keyshare + ) + + # 3. Server processes initial request: + blinded_pt = opaque.unmarshal_compressed(blinded_msg) + eval_pt = opaque.point_mul(blinded_pt, int.from_bytes(oprf_priv, "big")) + evaluated_msg = opaque.marshal_compressed(eval_pt) + + server_ephemeral_seed = opaque.nonce() + server_ephemeral_pub, server_ephemeral_priv = opaque.derive_key_pair( + server_ephemeral_seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + server_login_nonce = opaque.nonce() + + # Server computes shared keys + # Client recovered pub key from envelope + seed = opaque.expand( + randomized_password, envelope_nonce + opaque.PRIVATE_KEY_INFO, 32 + ) + client_pub, client_priv = opaque.derive_key_pair( + seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + + s_dh1 = opaque.diffie_hellman(server_ephemeral_priv, client_pub_keyshare) + s_dh2 = opaque.diffie_hellman(server_priv, client_pub_keyshare) + s_dh3 = opaque.diffie_hellman(server_ephemeral_priv, client_pub) + s_ikm = opaque.concat(s_dh1, s_dh2, s_dh3) + + preamble = opaque.concat( + b"OPAQUEv1-", + username.encode("utf-8"), + client_nonce, + client_pub_keyshare, + server_pub, + evaluated_msg, + server_login_nonce, + server_ephemeral_pub, + ) + + s_km2, s_km3, _ = opaque.derive_shared_keys(s_ikm, preamble) + server_mac = opaque.mac(s_km2, opaque.sha256_hash(preamble)) + + server_resp1 = login_pb2.LoginResponse( + opaque_response=login_pb2.OpaqueLoginResponse( + initial_response=login_pb2.InitialOpaqueLoginResponse( + server_nonce=server_login_nonce, + server_public_keyshare=server_ephemeral_pub, + server_mac=server_mac, + evaluated_message=evaluated_msg, + masking_nonce=masking_nonce, + masked_response=masked_response, + ) + ) + ) + + # 4. Client completes handshake + client_req2 = client_auth.final_request(server_resp1) + client_mac = client_req2.opaque_request.final_request.client_mac + + # 5. Server verifies client MAC + expected_client_mac = opaque.mac( + s_km3, + opaque.sha256_hash(opaque.concat(preamble, server_mac)), + ) + self.assertEqual(client_mac, expected_client_mac) + + def test_final_request_invalid_masked_response_length(self): + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + auth = opaque.UserAuthenticator("user", "pass", params) + auth.initial_request() + + resp = login_pb2.LoginResponse( + opaque_response=login_pb2.OpaqueLoginResponse( + initial_response=login_pb2.InitialOpaqueLoginResponse( + masked_response=b"invalid_len", + ) + ) + ) + with self.assertRaises(ValueError) as cm: + auth.final_request(resp) + self.assertIn("Invalid masked response length", str(cm.exception)) + + def test_clear(self): + opaque._clear(None) + b = bytearray(b"hello") + opaque._clear(b) + self.assertEqual(b, bytearray(5)) + + def test_point_add_identity_and_inversion(self): + pt = (opaque.GX, opaque.GY) + self.assertEqual(opaque.point_add(None, pt), pt) + self.assertEqual(opaque.point_add(pt, None), pt) + self.assertIsNone(opaque.point_add(None, None)) + + inv_pt = (opaque.GX, (opaque.P - opaque.GY) % opaque.P) + self.assertIsNone(opaque.point_add(pt, inv_pt)) + + def test_point_mul_infinity_and_zero(self): + self.assertIsNone(opaque.point_mul(None, 5)) + self.assertIsNone(opaque.point_mul(opaque.G, 0)) + + def test_marshal_compressed_none(self): + with self.assertRaises(ValueError) as cm: + opaque.marshal_compressed(None) + self.assertIn("Point at infinity cannot be compressed", str(cm.exception)) + + def test_unmarshal_compressed_errors(self): + # Invalid length + with self.assertRaises(ValueError) as cm: + opaque.unmarshal_compressed(b"\x02" * 32) + self.assertIn("Invalid compressed point length", str(cm.exception)) + + # Invalid prefix + with self.assertRaises(ValueError) as cm: + opaque.unmarshal_compressed(b"\x04" + b"\x00" * 32) + self.assertIn("Invalid compressed point prefix", str(cm.exception)) + + # x coordinate exceeds P + with self.assertRaises(ValueError) as cm: + opaque.unmarshal_compressed(b"\x02" + (opaque.P + 1).to_bytes(32, "big")) + self.assertIn("x coordinate exceeds field prime", str(cm.exception)) + + # Point not on curve (find an x that produces a quadratic non-residue) + for candidate_x in range(1, 100): + rhs = ( + pow(candidate_x, 3, opaque.P) + opaque.A * candidate_x + opaque.B + ) % opaque.P + if pow(rhs, opaque.P_MINUS_1_OVER_2, opaque.P) != 1: + with self.assertRaises(ValueError) as cm: + opaque.unmarshal_compressed( + b"\x02" + candidate_x.to_bytes(32, "big") + ) + self.assertIn("Point is not on curve", str(cm.exception)) + break + + def test_expand_message_xmd_oversize_dst(self): + res = opaque.expand_message_xmd(b"msg", b"D" * 256, 32) + self.assertEqual(len(res), 32) + + def test_expand_message_xmd_bytearray_input(self): + res_ba = opaque.expand_message_xmd(bytearray(b"msg"), b"dst", 32) + res_bytes = opaque.expand_message_xmd(b"msg", b"dst", 32) + self.assertEqual(res_ba, res_bytes) + self.assertEqual(len(res_ba), 32) + + def test_map_to_curve_sswu_zero(self): + pt = opaque.map_to_curve_sswu(0) + self.assertIsInstance(pt, tuple) + self.assertEqual(len(pt), 2) + + def test_hash_to_curve_p256_infinity(self): + from unittest import mock + + with mock.patch( + "google.cloud.spanner_v1.omni.opaque.point_add", return_value=None + ): + with self.assertRaises(ValueError) as cm: + opaque.hash_to_curve_p256(b"msg", b"dst") + self.assertIn("Hash to curve produced point at infinity", str(cm.exception)) + + def test_validate_hash_parameters_errors(self): + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(None) + self.assertIn("hash_parameters cannot be None", str(cm.exception)) + + # Missing argon2_id_parameters on proto message + proto_empty = authentication_pb2.HashParameters() + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(proto_empty) + self.assertIn( + "hash_parameters must contain non-nil argon2_id_parameters", + str(cm.exception), + ) + + # Missing argon2_id_parameters on non-proto object + class EmptyParams: + argon2_id_parameters = None + + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(EmptyParams()) + self.assertIn( + "hash_parameters must contain non-nil argon2_id_parameters", + str(cm.exception), + ) + + # Invalid memory usage + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=7, + parallelism=4, + hash_size=32, + ) + ) + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(params) + self.assertIn("Invalid Argon2Id memory usage", str(cm.exception)) + + # Invalid parallelism + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=0, + hash_size=32, + ) + ) + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(params) + self.assertIn("Invalid Argon2Id parallelism", str(cm.exception)) + + # Invalid iteration count (0 and 11) + params_low = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=0, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(params_low) + self.assertIn("Invalid Argon2Id iteration count", str(cm.exception)) + + params_high = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=11, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(params_high) + self.assertIn("Invalid Argon2Id iteration count", str(cm.exception)) + + # Valid non-proto hash parameters + class ValidNonProtoParams: + argon2_id_parameters = authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + + opaque._validate_hash_parameters(ValidNonProtoParams()) + + # Invalid hash_size (< 8 and > 512) + params_low = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=7, + ) + ) + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(params_low) + self.assertIn("Invalid Argon2Id hash size", str(cm.exception)) + + params_high = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=513, + ) + ) + with self.assertRaises(ValueError) as cm: + opaque._validate_hash_parameters(params_high) + self.assertIn("Invalid Argon2Id hash size", str(cm.exception)) + + def test_random_oracle_sha256_large_max_val(self): + max_val = (1 << 264) + 1 + res = opaque.random_oracle_sha256(b"seed", max_val) + self.assertEqual(len(res), 34) + + def test_derive_key_pair_zero_priv(self): + from unittest import mock + + with mock.patch( + "google.cloud.spanner_v1.omni.opaque.random_oracle_sha256", + return_value=b"\x00" * 32, + ): + pub, priv = opaque.derive_key_pair(b"seed", b"info") + self.assertEqual(priv, (1).to_bytes(32, "big")) + self.assertEqual(pub, opaque.marshal_compressed(opaque.G)) + + def test_blind_and_finalize_edge_cases(self): + with self.assertRaises(ValueError) as cm: + opaque.blind(b"") + self.assertIn("Password cannot be empty", str(cm.exception)) + + # Explicit blind scalar + explicit_scalar = (5).to_bytes(32, "big") + blinded, returned_scalar = opaque.blind(b"pass", blind_scalar=explicit_scalar) + self.assertEqual(returned_scalar, explicit_scalar) + + with self.assertRaises(ValueError) as cm: + opaque.finalize(b"", b"evaluated") + self.assertIn("Blind scalar cannot be empty", str(cm.exception)) + + def test_recover_client_mismatched_auth_tag(self): + with self.assertRaises(ValueError) as cm: + opaque.recover_client( + "user", + b"\x01" * 32, + b"\x02" * 32, + b"\x00" * 32, + opaque.marshal_compressed(opaque.G), + ) + self.assertIn("Auth tag mismatch", str(cm.exception)) + + def test_final_request_edge_cases(self): + from unittest import mock + + params = authentication_pb2.HashParameters( + argon2_id_parameters=authentication_pb2.HashParameters.Argon2IdParameters( + iteration_count=3, + memory_usage=64 * 1024, + parallelism=4, + hash_size=32, + ) + ) + auth = opaque.UserAuthenticator("user", "pass", params) + auth.initial_request() + + with self.assertRaises(ValueError) as cm: + auth.final_request(None) + self.assertIn("initial_response cannot be None", str(cm.exception)) + + empty_resp = login_pb2.LoginResponse() + with self.assertRaises(ValueError) as cm: + auth.final_request(empty_resp) + self.assertIn("Expected initial opaque response from server", str(cm.exception)) + + final_only_resp = login_pb2.LoginResponse() + final_only_resp.opaque_response.final_response.SetInParent() + with self.assertRaises(ValueError) as cm: + auth.final_request(final_only_resp) + self.assertIn("Expected initial opaque response from server", str(cm.exception)) + + # Test blind when secrets.randbelow initially returns 0 + with mock.patch("secrets.randbelow", side_effect=[0, 7]): + blinded_msg, blind_s = opaque.blind(b"testpass") + self.assertEqual(blind_s, (7).to_bytes(32, "big")) + + # Test server MAC mismatch + oprf_seed = opaque.nonce() + oprf_key_seed = opaque.expand(oprf_seed, b"userOprfKey", 32) + _, oprf_priv = opaque.derive_key_pair(oprf_key_seed, b"OPAQUE-DeriveKeyPair") + h_pt = opaque.hash_to_curve_p256(b"pass", opaque.LOGIN_DOMAIN_SEPARATION_TAG) + prf_pt = opaque.point_mul(h_pt, int.from_bytes(oprf_priv, "big")) + prf = opaque.marshal_compressed(prf_pt) + stretched_oprf = opaque.stretch(prf, params) + randomized_password = opaque.extract(opaque.concat(prf, stretched_oprf)) + + server_key_seed = opaque.nonce() + server_pub, _ = opaque.derive_key_pair( + server_key_seed, opaque.DIFFIE_HELLMAN_KEY_INFO + ) + envelope_nonce = opaque.nonce() + auth_key = opaque.expand( + randomized_password, envelope_nonce + opaque.AUTH_KEY_INFO, 32 + ) + auth_tag = opaque.mac(auth_key, envelope_nonce + server_pub + b"user") + serialized_envelope = opaque.concat(server_pub, envelope_nonce, auth_tag) + masking_key = opaque.expand(randomized_password, opaque.MASKING_KEY_INFO, 32) + masking_nonce = opaque.nonce() + credential_pad = opaque.expand( + masking_key, + opaque.concat(masking_nonce, b"CredentialResponsePad"), + len(serialized_envelope), + ) + masked_response = opaque.xor_bytes(serialized_envelope, credential_pad) + + blinded_pt = opaque.point_mul(h_pt, int.from_bytes(auth._blind, "big")) + eval_pt = opaque.point_mul(blinded_pt, int.from_bytes(oprf_priv, "big")) + server_ephemeral_pub, _ = opaque.derive_key_pair( + opaque.nonce(), opaque.DIFFIE_HELLMAN_KEY_INFO + ) + + resp = login_pb2.LoginResponse( + opaque_response=login_pb2.OpaqueLoginResponse( + initial_response=login_pb2.InitialOpaqueLoginResponse( + server_nonce=opaque.nonce(), + server_public_keyshare=server_ephemeral_pub, + server_mac=b"bad_server_mac" * 2 + b"\x00" * 4, + evaluated_message=opaque.marshal_compressed(eval_pt), + masking_nonce=masking_nonce, + masked_response=masked_response, + ) + ) + ) + + # Test server MAC mismatch on auth (which matches auth._blind) + with self.assertRaises(ValueError) as cm: + auth.final_request(resp) + self.assertIn("Server MAC mismatch", str(cm.exception)) + + # Test xor_bytes returning invalid envelope length + auth_short = opaque.UserAuthenticator("user", "pass", params) + auth_short.initial_request() + blinded_pt_short = opaque.point_mul( + h_pt, int.from_bytes(auth_short._blind, "big") + ) + eval_pt_short = opaque.point_mul( + blinded_pt_short, int.from_bytes(oprf_priv, "big") + ) + resp_short = login_pb2.LoginResponse( + opaque_response=login_pb2.OpaqueLoginResponse( + initial_response=login_pb2.InitialOpaqueLoginResponse( + server_nonce=opaque.nonce(), + server_public_keyshare=server_ephemeral_pub, + server_mac=b"bad_server_mac" * 2 + b"\x00" * 4, + evaluated_message=opaque.marshal_compressed(eval_pt_short), + masking_nonce=masking_nonce, + masked_response=masked_response, + ) + ) + ) + with mock.patch( + "google.cloud.spanner_v1.omni.opaque.xor_bytes", return_value=b"too_short" + ): + with self.assertRaises(ValueError) as cm: + auth_short.final_request(resp_short) + self.assertIn("Invalid serialized envelope length", str(cm.exception)) + + def test_missing_cryptography_dependency(self): + import importlib + import sys + + with mock.patch.dict( + sys.modules, + { + "cryptography": None, + "cryptography.hazmat": None, + "cryptography.hazmat.primitives": None, + "cryptography.hazmat.primitives.kdf": None, + "cryptography.hazmat.primitives.kdf.argon2": None, + "cryptography.hazmat.primitives.kdf.hkdf": None, + }, + ): + with self.assertRaises(ImportError) as cm: + importlib.reload(opaque) + self.assertIn( + "The 'cryptography' package is required for Spanner Omni authentication", + str(cm.exception), + ) + self.assertIn( + "pip install google-cloud-spanner[omni]", + str(cm.exception), + ) + + # Reload opaque cleanly + importlib.reload(opaque) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_connect.py b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_connect.py index 4496884027f7..19c81bc2fc27 100644 --- a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_connect.py +++ b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_connect.py @@ -183,3 +183,118 @@ def test_w_auto_partition_mode(self, mock_client): self.assertIsInstance(connection, Connection) self.assertTrue(connection.auto_partition_mode) + + def test_connect_omni_with_username_and_password(self, mock_client): + from google.cloud.spanner_dbapi import Connection, connect + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + connection = connect( + INSTANCE, + DATABASE, + instance_type="omni", + client_options={"api_endpoint": "omni-host:15000"}, + username="test_user", + password="test_password", + ) + + self.assertIsInstance(connection, Connection) + mock_client.assert_called_once_with( + project="default", + credentials=mock.ANY, + client_info=mock.ANY, + route_to_leader_enabled=True, + client_options=mock.ANY, + use_plain_text=False, + ca_certificate=None, + client_certificate=None, + client_key=None, + instance_type="omni", + ) + creds = mock_client.call_args_list[0][1]["credentials"] + self.assertIsInstance(creds, SpannerOmniCredentials) + self.assertEqual(creds.username, "test_user") + + def test_connect_omni_partial_auth_raises_value_error(self, mock_client): + from google.cloud.spanner_dbapi import connect + + with self.assertRaises(ValueError) as ctx: + connect( + INSTANCE, + DATABASE, + instance_type="omni", + client_options={"api_endpoint": "omni-host:15000"}, + username="test_user", + ) + self.assertIn( + "Both username and password must be specified for Omni authentication", + str(ctx.exception), + ) + + with self.assertRaises(ValueError) as ctx: + connect( + INSTANCE, + DATABASE, + instance_type="omni", + client_options={"api_endpoint": "omni-host:15000"}, + password="test_password", + ) + self.assertIn( + "Both username and password must be specified for Omni authentication", + str(ctx.exception), + ) + + def test_connect_omni_client_options_variants(self, mock_client): + from google.api_core.client_options import ClientOptions + + from google.cloud.spanner_dbapi import connect + + # client_options is None + connect( + INSTANCE, + DATABASE, + instance_type="omni", + experimental_host="omni-host:15000", + client_options=None, + ) + + # client_options is dict + connect( + INSTANCE, + DATABASE, + instance_type="omni", + experimental_host="omni-host:15000", + client_options={"quota_project_id": "test-project"}, + ) + + # client_options is ClientOptions object with api_endpoint + opts_with_ep = ClientOptions(api_endpoint="omni-host:15000") + connect( + INSTANCE, + DATABASE, + instance_type="omni", + client_options=opts_with_ep, + ) + + # client_options is ClientOptions object without api_endpoint (using experimental_host) + opts_empty_ep = ClientOptions() + connect( + INSTANCE, + DATABASE, + instance_type="omni", + experimental_host="omni-host:15000", + client_options=opts_empty_ep, + ) + + # Missing host when instance_type='omni' raises ValueError + with self.assertRaises(ValueError) as ctx: + connect( + INSTANCE, + DATABASE, + instance_type="omni", + ) + self.assertIn( + "Host must be set for connecting to Spanner Omni instances", + str(ctx.exception), + ) diff --git a/packages/google-cloud-spanner/tests/unit/test__helpers.py b/packages/google-cloud-spanner/tests/unit/test__helpers.py index 0a6e9594b167..3776bbd26141 100644 --- a/packages/google-cloud-spanner/tests/unit/test__helpers.py +++ b/packages/google-cloud-spanner/tests/unit/test__helpers.py @@ -1862,3 +1862,190 @@ def test_large_values(self): self.assertEqual(result.months, case["expected_months"]) self.assertEqual(result.days, case["expected_days"]) self.assertEqual(result.nanos, case["expected_nanos"]) + + +class TestCreateSpannerOmniTransport(unittest.TestCase): + def test_create_spanner_omni_transport_plaintext_with_auth_interceptor(self): + import grpc + + from google.cloud.spanner_v1 import _helpers + + mock_factory = mock.MagicMock() + mock_creds = mock.MagicMock() + mock_interceptor = mock.MagicMock(spec=grpc.UnaryUnaryClientInterceptor) + mock_creds.create_auth_interceptor.return_value = mock_interceptor + + with mock.patch("grpc.insecure_channel") as mock_insecure: + with mock.patch("grpc.intercept_channel") as mock_intercept: + _helpers._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + credentials=mock_creds, + ) + mock_insecure.assert_called_once_with(target="localhost:9010") + mock_intercept.assert_called_once_with( + mock_insecure.return_value, mock_interceptor + ) + mock_factory.assert_called_once_with( + channel=mock_intercept.return_value, credentials=mock_creds + ) + + def test_create_spanner_omni_transport_tls_and_mtls(self): + from google.cloud.spanner_v1 import _helpers + + mock_factory = mock.MagicMock() + with mock.patch("builtins.open", mock.mock_open(read_data=b"cert_data")): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_creds: + with mock.patch("grpc.secure_channel") as mock_secure: + # TLS only + _helpers._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate=None, + client_key=None, + ) + mock_ssl_creds.assert_called_with(root_certificates=b"cert_data") + mock_secure.assert_called_with( + "omni-host:15000", mock_ssl_creds.return_value + ) + + # mTLS + _helpers._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate="client.pem", + client_key="key.pem", + ) + mock_ssl_creds.assert_called_with( + root_certificates=b"cert_data", + private_key=b"cert_data", + certificate_chain=b"cert_data", + ) + + def test_create_spanner_omni_transport_validation_errors(self): + from google.cloud.spanner_v1 import _helpers + + mock_factory = mock.MagicMock() + # Missing ca_certificate + with self.assertRaises(ValueError) as cm: + _helpers._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate=None, + client_certificate=None, + client_key=None, + ) + self.assertIn("TLS/mTLS connection requires ca_certificate", str(cm.exception)) + + # Missing client_key when client_certificate provided + with mock.patch("builtins.open", mock.mock_open(read_data=b"cert_data")): + with self.assertRaises(ValueError) as cm: + _helpers._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate="client.pem", + client_key=None, + ) + self.assertIn( + "Both client_certificate and client_key must be provided for mTLS connection", + str(cm.exception), + ) + + # Missing client_certificate when client_key provided + with mock.patch("builtins.open", mock.mock_open(read_data=b"cert_data")): + with self.assertRaises(ValueError) as cm: + _helpers._create_spanner_omni_transport( + mock_factory, + "omni-host:15000", + use_plain_text=False, + ca_certificate="ca.pem", + client_certificate=None, + client_key="key.pem", + ) + self.assertIn( + "Both client_certificate and client_key must be provided for mTLS connection", + str(cm.exception), + ) + + def test_create_spanner_omni_transport_interceptors_and_credentials_fallback(self): + import grpc + from google.auth.credentials import AnonymousCredentials + + from google.cloud.spanner_v1 import _helpers + + mock_factory = mock.MagicMock() + existing_interceptor = mock.MagicMock(spec=grpc.UnaryUnaryClientInterceptor) + mock_creds = mock.MagicMock(spec=["create_auth_interceptor"]) + auth_interceptor = mock.MagicMock(spec=grpc.UnaryUnaryClientInterceptor) + mock_creds.create_auth_interceptor.return_value = auth_interceptor + + # Case 1: credentials with interceptor and existing interceptors + with mock.patch("grpc.insecure_channel") as mock_insecure: + with mock.patch("grpc.intercept_channel") as mock_intercept: + _helpers._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + interceptors=[existing_interceptor], + credentials=mock_creds, + ) + mock_intercept.assert_called_once_with( + mock_insecure.return_value, existing_interceptor, auth_interceptor + ) + mock_factory.assert_called_once_with( + channel=mock_intercept.return_value, credentials=mock_creds + ) + + # Case 2: credentials without create_auth_interceptor, no interceptors + mock_plain_creds = mock.MagicMock(spec=[]) + mock_factory.reset_mock() + with mock.patch("grpc.insecure_channel") as mock_insecure: + with mock.patch("grpc.intercept_channel") as mock_intercept: + _helpers._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + interceptors=None, + credentials=mock_plain_creds, + ) + mock_intercept.assert_not_called() + mock_factory.assert_called_once_with( + channel=mock_insecure.return_value, credentials=mock_plain_creds + ) + + # Case 3: credentials is None -> uses AnonymousCredentials + mock_factory.reset_mock() + with mock.patch("grpc.insecure_channel") as mock_insecure: + with mock.patch("grpc.intercept_channel") as mock_intercept: + _helpers._create_spanner_omni_transport( + mock_factory, + "localhost:9010", + use_plain_text=True, + ca_certificate=None, + client_certificate=None, + client_key=None, + interceptors=None, + credentials=None, + ) + mock_intercept.assert_not_called() + self.assertEqual(mock_factory.call_count, 1) + self.assertIsInstance( + mock_factory.call_args[1]["credentials"], AnonymousCredentials + ) diff --git a/packages/google-cloud-spanner/tests/unit/test_client.py b/packages/google-cloud-spanner/tests/unit/test_client.py index 69bb317f58e0..ac279e031230 100644 --- a/packages/google-cloud-spanner/tests/unit/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/test_client.py @@ -988,3 +988,117 @@ def test_constructor_w_invalid_instance_type_raises_value_error(self): self.assertIn( "instance_type must be one of 'cloud' or 'omni'", str(ctx.exception) ) + + def test_constructor_w_omni_username_password(self): + from google.cloud.spanner_v1.client import InstanceType + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + password="test_password", + ) + self.assertEqual(client.project, "default") + self.assertEqual(client.instance_type, InstanceType.OMNI) + self.assertEqual(client._host, "omni-host:15000") + self.assertIsInstance(client._credentials, SpannerOmniCredentials) + self.assertEqual(client._credentials.username, "test_user") + self.assertEqual(client._credentials.target, "omni-host:15000") + + def test_constructor_w_omni_partial_credentials_raises_value_error(self): + from google.cloud.spanner_v1.client import InstanceType + + with self.assertRaises(ValueError) as ctx: + self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + ) + self.assertIn( + "Both username and password must be specified for Omni authentication", + str(ctx.exception), + ) + + with self.assertRaises(ValueError) as ctx: + self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + password="test_password", + ) + self.assertIn( + "Both username and password must be specified for Omni authentication", + str(ctx.exception), + ) + + def test_constructor_w_username_password_on_cloud_raises_value_error(self): + creds = build_scoped_credentials() + with self.assertRaises(ValueError) as ctx: + self._make_one( + project=self.PROJECT, + credentials=creds, + username="test_user", + password="test_password", + ) + self.assertIn( + "username and password can only be used when instance_type='omni'.", + str(ctx.exception), + ) + + def test_instance_admin_api_omni(self): + from google.cloud.spanner_v1.client import InstanceType + + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + password="test_password", + use_plain_text=True, + ) + + inst_module = "google.cloud.spanner_v1.client.InstanceAdminClient" + with mock.patch(inst_module) as instance_admin_client: + api = client.instance_admin_api + self.assertIs(api, instance_admin_client.return_value) + instance_admin_client.assert_called_once() + called_kw = instance_admin_client.call_args[1] + self.assertIn("transport", called_kw) + + def test_database_admin_api_omni(self): + from google.cloud.spanner_v1.client import InstanceType + + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + username="test_user", + password="test_password", + use_plain_text=True, + ) + + db_module = "google.cloud.spanner_v1.client.DatabaseAdminClient" + with mock.patch(db_module) as database_admin_client: + api = client.database_admin_api + self.assertIs(api, database_admin_client.return_value) + database_admin_client.assert_called_once() + called_kw = database_admin_client.call_args[1] + self.assertIn("transport", called_kw) + + def test_constructor_w_omni_explicit_credentials_instance(self): + from google.cloud.spanner_v1.client import InstanceType + from google.cloud.spanner_v1.omni.credentials import SpannerOmniCredentials + + creds = SpannerOmniCredentials("user", "pass", "omni-host:15000") + client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni-host:15000"}, + instance_type=InstanceType.OMNI, + credentials=creds, + ) + self.assertIs(client._credentials, creds) diff --git a/packages/google-cloud-spanner/tests/unit/test_snapshot.py b/packages/google-cloud-spanner/tests/unit/test_snapshot.py index a5082e5b8aa1..4a65d46aea8c 100644 --- a/packages/google-cloud-spanner/tests/unit/test_snapshot.py +++ b/packages/google-cloud-spanner/tests/unit/test_snapshot.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime, timedelta -from threading import Lock +from threading import Event, Lock, Thread from typing import Mapping import mock @@ -695,12 +695,69 @@ def test_ctor(self): self.assertFalse(derived._multi_use) self.assertEqual(derived._execute_sql_request_count, 0) self.assertEqual(derived._read_request_count, 0) + self.assertFalse(derived._begin_request_sent) self.assertIsNone(derived._transaction_id) self.assertIsNone(derived._precommit_token) self.assertIsInstance(derived._lock, type(Lock())) + self.assertFalse(derived._transaction_begin_event.is_set()) self.assertNoSpans() + def test__wait_for_transaction_begin_claims_inline_begin(self): + derived = _build_snapshot_derived(multi_use=True) + + derived._wait_for_transaction_begin() + + # The first request is the one that begins the transaction inline. + self.assertTrue(derived._begin_request_sent) + + def test__wait_for_transaction_begin_wo_multi_use(self): + derived = _build_snapshot_derived(multi_use=False) + derived._read_request_count = 1 + + with self.assertRaisesRegex(ValueError, "Cannot re-use single-use snapshot."): + derived._wait_for_transaction_begin() + + def test__wait_for_transaction_begin_waits_for_concurrent_begin(self): + """A concurrent request must wait for the in-flight inline begin. + + Regression test: without the begin event, the second request observes + ``_transaction_id is None`` and wrongly raises "Transaction has not begun." + """ + + from google.cloud.spanner_v1 import Transaction as TransactionPB + + derived = _build_snapshot_derived(multi_use=True) + + # First request claims the inline begin, but has not completed yet, so + # no transaction id is available. + derived._wait_for_transaction_begin() + + errors = [] + released = Event() + + def concurrent_request(): + try: + derived._wait_for_transaction_begin() + except Exception as exc: # pragma: no cover - only on regression + errors.append(exc) + finally: + released.set() + + thread = Thread(target=concurrent_request, daemon=True) + thread.start() + + # The concurrent request blocks while the transaction id is unknown. + self.assertFalse(released.wait(timeout=0.1)) + + # Completing the inline begin releases it. + derived._update_for_transaction_pb(TransactionPB(id=TXN_ID)) + self.assertTrue(released.wait(timeout=10)) + + thread.join(timeout=10) + self.assertFalse(thread.is_alive()) + self.assertEqual(errors, []) + def test__build_transaction_selector_pb_single_use(self): derived = _build_snapshot_derived(multi_use=False) @@ -1203,8 +1260,15 @@ def test_read_w_multi_use_w_first_w_partition(self, mock_region): "google.cloud.spanner_v1._opentelemetry_tracing._get_cloud_region", return_value="global", ) + @mock.patch( + "google.cloud.spanner_v1.snapshot._TRANSACTION_BEGIN_TIMEOUT_SECONDS", 0.01 + ) def test_read_w_multi_use_w_first_w_count_gt_0(self, mock_region): - with self.assertRaises(ValueError): + # No concurrent request ever begins the transaction, so this request + # waits for the begin timeout to expire before giving up. + with self.assertRaisesRegex( + ValueError, "Timed out waiting for transaction to begin." + ): self._execute_read(multi_use=True, first=True, count=1) @mock.patch( @@ -1510,8 +1574,15 @@ def test_execute_sql_w_multi_use_wo_first_w_count_gt_0(self, mock_region): def test_execute_sql_w_multi_use_w_first(self, mock_region): self._execute_sql_helper(multi_use=True, first=True) + @mock.patch( + "google.cloud.spanner_v1.snapshot._TRANSACTION_BEGIN_TIMEOUT_SECONDS", 0.01 + ) def test_execute_sql_w_multi_use_w_first_w_count_gt_0(self): - with self.assertRaises(ValueError): + # No concurrent request ever begins the transaction, so this request + # waits for the begin timeout to expire before giving up. + with self.assertRaisesRegex( + ValueError, "Timed out waiting for transaction to begin." + ): self._execute_sql_helper(multi_use=True, first=True, count=1) @mock.patch( diff --git a/packages/google-cloud-spanner/tests/unit/test_transaction.py b/packages/google-cloud-spanner/tests/unit/test_transaction.py index aa9e9ae14995..a444873c2474 100644 --- a/packages/google-cloud-spanner/tests/unit/test_transaction.py +++ b/packages/google-cloud-spanner/tests/unit/test_transaction.py @@ -729,6 +729,24 @@ def test_execute_update_other_error(self, mock_region): with self.assertRaises(RuntimeError): transaction.execute_update(DML_QUERY) + @mock.patch( + "google.cloud.spanner_v1._opentelemetry_tracing._get_cloud_region", + return_value="global", + ) + def test_execute_update_inline_begin_error_releases_lock(self, mock_region): + database = _Database() + database.spanner_api = self._make_spanner_api() + database.spanner_api.execute_sql.side_effect = RuntimeError() + session = _Session(database) + transaction = self._make_one(session) + self.assertIsNone(transaction._transaction_id) + self.assertFalse(transaction._lock.locked()) + + with self.assertRaises(RuntimeError): + transaction.execute_update(DML_QUERY) + + self.assertFalse(transaction._lock.locked()) + def _execute_update_helper( self, count=0, @@ -1001,6 +1019,24 @@ def test_batch_update_other_error(self, mock_region): with self.assertRaises(RuntimeError): transaction.batch_update(statements=[DML_QUERY]) + @mock.patch( + "google.cloud.spanner_v1._opentelemetry_tracing._get_cloud_region", + return_value="global", + ) + def test_batch_update_inline_begin_error_releases_lock(self, mock_region): + database = _Database() + database.spanner_api = self._make_spanner_api() + database.spanner_api.execute_batch_dml.side_effect = RuntimeError() + session = _Session(database) + transaction = self._make_one(session) + self.assertIsNone(transaction._transaction_id) + self.assertFalse(transaction._lock.locked()) + + with self.assertRaises(RuntimeError): + transaction.batch_update(statements=[DML_QUERY]) + + self.assertFalse(transaction._lock.locked()) + def _batch_update_helper( self, error_after=None, diff --git a/packages/google-maps-solar/CHANGELOG.md b/packages/google-maps-solar/CHANGELOG.md index 457c19621e3d..21ea085a4770 100644 --- a/packages/google-maps-solar/CHANGELOG.md +++ b/packages/google-maps-solar/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-maps-solar/#history +## [0.6.1](https://github.com/googleapis/google-cloud-python/compare/google-maps-solar-v0.6.0...google-maps-solar-v0.6.1) (2026-09-17) + + +### Features + +* update API sources and regenerate ([#18396](https://github.com/googleapis/google-cloud-python/issues/18396)) ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) +* update API sources and regenerate. ([e9f8e59](https://github.com/googleapis/google-cloud-python/commit/e9f8e590b7b395e660cc5437535166dfb920d246)) + ## [0.6.0](https://github.com/googleapis/google-cloud-python/compare/google-maps-solar-v0.5.0...google-maps-solar-v0.6.0) (2026-06-02) diff --git a/packages/google-maps-solar/google/maps/solar/__init__.py b/packages/google-maps-solar/google/maps/solar/__init__.py index 7eae9b61fb3f..7b6113e06137 100644 --- a/packages/google-maps-solar/google/maps/solar/__init__.py +++ b/packages/google-maps-solar/google/maps/solar/__init__.py @@ -21,6 +21,7 @@ from google.maps.solar_v1.services.solar.async_client import SolarAsyncClient from google.maps.solar_v1.services.solar.client import SolarClient from google.maps.solar_v1.types.solar_service import ( + AdditionalInsights, BuildingInsights, CashPurchaseSavings, DataLayers, @@ -66,6 +67,7 @@ "SolarPanel", "SolarPanelConfig", "SolarPotential", + "AdditionalInsights", "DataLayerView", "Experiment", "ImageryQuality", diff --git a/packages/google-maps-solar/google/maps/solar/gapic_version.py b/packages/google-maps-solar/google/maps/solar/gapic_version.py index 916d95dd4eda..4c89af3224e4 100644 --- a/packages/google-maps-solar/google/maps/solar/gapic_version.py +++ b/packages/google-maps-solar/google/maps/solar/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.0" # {x-release-please-version} +__version__ = "0.6.1" # {x-release-please-version} diff --git a/packages/google-maps-solar/google/maps/solar_v1/__init__.py b/packages/google-maps-solar/google/maps/solar_v1/__init__.py index ed4e404dd7ce..c96b20a63f8f 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/__init__.py +++ b/packages/google-maps-solar/google/maps/solar_v1/__init__.py @@ -33,6 +33,7 @@ from .services.solar import SolarAsyncClient, SolarClient from .types.solar_service import ( + AdditionalInsights, BuildingInsights, CashPurchaseSavings, DataLayers, @@ -59,6 +60,7 @@ __all__ = ( "SolarAsyncClient", + "AdditionalInsights", "BuildingInsights", "CashPurchaseSavings", "DataLayerView", diff --git a/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py b/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py index 916d95dd4eda..4c89af3224e4 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py +++ b/packages/google-maps-solar/google/maps/solar_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.0" # {x-release-please-version} +__version__ = "0.6.1" # {x-release-please-version} diff --git a/packages/google-maps-solar/google/maps/solar_v1/types/__init__.py b/packages/google-maps-solar/google/maps/solar_v1/types/__init__.py index 08ead4c28d53..7107b2de5a0f 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/types/__init__.py +++ b/packages/google-maps-solar/google/maps/solar_v1/types/__init__.py @@ -14,6 +14,7 @@ # limitations under the License. # from .solar_service import ( + AdditionalInsights, BuildingInsights, CashPurchaseSavings, DataLayers, @@ -57,6 +58,7 @@ "SolarPanel", "SolarPanelConfig", "SolarPotential", + "AdditionalInsights", "DataLayerView", "Experiment", "ImageryQuality", diff --git a/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py b/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py index fcf25b7a9e36..3645d1ea0659 100644 --- a/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py +++ b/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py @@ -25,6 +25,7 @@ __protobuf__ = proto.module( package="google.maps.solar.v1", manifest={ + "AdditionalInsights", "DataLayerView", "ImageryQuality", "SolarPanelOrientation", @@ -51,6 +52,28 @@ ) +class AdditionalInsights(proto.Enum): + r"""Additional building information such as roof geometry and + solar panel arrays that can be returned in BuildingInsights. + + New values may be added to this enum in the future. + + Values: + ADDITIONAL_INSIGHTS_UNSPECIFIED (0): + The default value. The default + BuildingInsights will be returned. + DETECTED_ARRAYS (2): + Determines whether the response will include the detected + arrays. + + If specified, the ``detected_arrays`` field will be + populated in the response. + """ + + ADDITIONAL_INSIGHTS_UNSPECIFIED = 0 + DETECTED_ARRAYS = 2 + + class DataLayerView(proto.Enum): r"""What subset of the solar information to return. @@ -182,8 +205,17 @@ class FindClosestBuildingInsightsRequest(proto.Message): ``MEDIUM`` quality imagery is returned if ``required_quality`` is set to ``MEDIUM``. experiments (MutableSequence[google.maps.solar_v1.types.Experiment]): - Optional. Specifies the pre-GA features to - enable. + Optional. Specifies the pre-GA experiments to enable. + Requests using this field are classified as a pre-GA + offering under the `Google Maps Platform Service Specific + Terms `__. + See `launch stage + descriptions `__ + for more details. + additional_insights (MutableSequence[google.maps.solar_v1.types.AdditionalInsights]): + Optional. A list of + [additional_insights][google.maps.solar.v1.FindClosestBuildingInsightsRequest.additional_insights] + to be included in the response. """ location: latlng_pb2.LatLng = proto.Field( @@ -205,6 +237,11 @@ class FindClosestBuildingInsightsRequest(proto.Message): number=5, enum="Experiment", ) + additional_insights: MutableSequence["AdditionalInsights"] = proto.RepeatedField( + proto.ENUM, + number=6, + enum="AdditionalInsights", + ) class LatLngBox(proto.Message): @@ -267,8 +304,59 @@ class BuildingInsights(proto.Message): imagery_quality (google.maps.solar_v1.types.ImageryQuality): The quality of the imagery used to compute the data for this building. + detected_arrays (google.maps.solar_v1.types.BuildingInsights.DetectedArrays): + Solar arrays detected on the building. This field is only + populated if DETECTED_ARRAYS is included in the request's + [FindClosestBuildingInsightsRequest.additional_insights][google.maps.solar.v1.FindClosestBuildingInsightsRequest.additional_insights]. """ + class DetectedArrays(proto.Message): + r"""Information about solar arrays detected on the building. + + Attributes: + detection_status (google.maps.solar_v1.types.BuildingInsights.DetectedArrays.DetectionStatus): + Indicates the detection status of solar + arrays for this building. + latest_capture_date (google.type.date_pb2.Date): + The date indicating when the latest solar + array data was captured. + """ + + class DetectionStatus(proto.Enum): + r"""Indicates the detection status of solar arrays for this + building. + + Values: + DETECTION_STATUS_UNSPECIFIED (0): + Unspecified status. + DETECTION_STATUS_DATA_UNAVAILABLE (1): + Detected solar array data is unavailable for + this building. + DETECTION_STATUS_ARRAYS_DETECTED (2): + At least one solar array has been detected + for this building. + DETECTION_STATUS_NO_ARRAYS_DETECTED (3): + No solar arrays detected for this building. + """ + + DETECTION_STATUS_UNSPECIFIED = 0 + DETECTION_STATUS_DATA_UNAVAILABLE = 1 + DETECTION_STATUS_ARRAYS_DETECTED = 2 + DETECTION_STATUS_NO_ARRAYS_DETECTED = 3 + + detection_status: "BuildingInsights.DetectedArrays.DetectionStatus" = ( + proto.Field( + proto.ENUM, + number=1, + enum="BuildingInsights.DetectedArrays.DetectionStatus", + ) + ) + latest_capture_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + message=date_pb2.Date, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -319,6 +407,11 @@ class BuildingInsights(proto.Message): number=10, enum="ImageryQuality", ) + detected_arrays: DetectedArrays = proto.Field( + proto.MESSAGE, + number=12, + message=DetectedArrays, + ) class SolarPotential(proto.Message): @@ -385,11 +478,10 @@ class SolarPotential(proto.Message): Size and sunlight quantiles for each roof segment. solar_panels (MutableSequence[google.maps.solar_v1.types.SolarPanel]): - Each [SolarPanel] [google.maps.solar.v1.SolarPanel] - describes a single solar panel. They are listed in the order - that the panel layout algorithm placed this. This is - usually, though not always, in decreasing order of annual - energy production. + Each [SolarPanel][google.maps.solar.v1.SolarPanel] describes + a single solar panel. They are listed in the order that the + panel layout algorithm placed this. This is usually, though + not always, in decreasing order of annual energy production. solar_panel_configs (MutableSequence[google.maps.solar_v1.types.SolarPanelConfig]): Each [SolarPanelConfig] [google.maps.solar.v1.SolarPanelConfig] describes a @@ -1166,8 +1258,13 @@ class GetDataLayersRequest(proto.Message): ``MEDIUM`` quality imagery is returned if ``required_quality`` is set to ``MEDIUM``. experiments (MutableSequence[google.maps.solar_v1.types.Experiment]): - Optional. Specifies the pre-GA experiments to - enable. + Optional. Specifies the pre-GA experiments to enable. + Requests using this field are classified as a pre-GA + offering under the `Google Maps Platform Service Specific + Terms `__. + See `launch stage + descriptions `__ + for more details. """ location: latlng_pb2.LatLng = proto.Field( diff --git a/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json b/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json index f9f9efa46695..c4cafe8d32fe 100644 --- a/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json +++ b/packages/google-maps-solar/samples/generated_samples/snippet_metadata_google.maps.solar.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-solar", - "version": "0.6.0" + "version": "0.6.1" }, "snippets": [ { diff --git a/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py b/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py index f60b5dd43713..3c349e894e86 100644 --- a/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py +++ b/packages/google-maps-solar/tests/unit/gapic/solar_v1/test_solar.py @@ -1688,6 +1688,7 @@ def test_find_closest_building_insights_rest_required_fields( # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( + "additionalInsights", "exactQualityRequired", "experiments", "location", diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/project_views.rst b/preview-packages/google-cloud-compute/docs/compute_v1/project_views.rst new file mode 100644 index 000000000000..fd564cefcb85 --- /dev/null +++ b/preview-packages/google-cloud-compute/docs/compute_v1/project_views.rst @@ -0,0 +1,6 @@ +ProjectViews +------------------------------ + +.. automodule:: google.cloud.compute_v1.services.project_views + :members: + :inherited-members: diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst b/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst index 8aa28091777e..928851b02ee5 100644 --- a/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst +++ b/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst @@ -59,6 +59,7 @@ Services for Google Cloud Compute v1 API packet_mirrorings preview_features projects + project_views public_advertised_prefixes public_delegated_prefixes region_autoscalers diff --git a/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py index 027dd842c37a..c70c8c6e9788 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -141,6 +141,7 @@ from google.cloud.compute_v1.services.preview_features.client import ( PreviewFeaturesClient, ) +from google.cloud.compute_v1.services.project_views.client import ProjectViewsClient from google.cloud.compute_v1.services.projects.client import ProjectsClient from google.cloud.compute_v1.services.public_advertised_prefixes.client import ( PublicAdvertisedPrefixesClient, @@ -517,6 +518,27 @@ CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, + CapacityAdviceRequest, + CapacityAdviceRequestDistributionPolicy, + CapacityAdviceRequestDistributionPolicyZoneConfiguration, + CapacityAdviceRequestInstanceFlexibilityPolicy, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk, + CapacityAdviceRequestInstanceProperties, + CapacityAdviceRequestInstancePropertiesScheduling, + CapacityAdviceResponse, + CapacityAdviceResponseRecommendation, + CapacityAdviceResponseRecommendationScores, + CapacityAdviceResponseRecommendationShard, + CapacityAdviceRpcRequest, + CapacityHistoryAdviceRequest, + CapacityHistoryRequest, + CapacityHistoryRequestInstanceProperties, + CapacityHistoryRequestInstancePropertiesScheduling, + CapacityHistoryRequestLocationPolicy, + CapacityHistoryResponse, + CapacityHistoryResponsePreemptionRecord, + CapacityHistoryResponsePriceRecord, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -875,6 +897,7 @@ GetPacketMirroringRuleNetworkFirewallPolicyRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -1310,6 +1333,7 @@ InterconnectRemoteLocationPermittedConnections, InterconnectsGetDiagnosticsResponse, InterconnectsGetMacsecConfigResponse, + Interval, InvalidateCacheUrlMapRequest, Items, License, @@ -1490,6 +1514,7 @@ Metadata, MetadataFilter, MetadataFilterLabelMatch, + Money, MoveAddressRequest, MoveDiskProjectRequest, MoveFirewallPolicyRequest, @@ -1685,6 +1710,7 @@ ProjectsListXpnHostsRequest, ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -2415,6 +2441,7 @@ "PacketMirroringsClient", "PreviewFeaturesClient", "ProjectsClient", + "ProjectViewsClient", "PublicAdvertisedPrefixesClient", "PublicDelegatedPrefixesClient", "RegionAutoscalersClient", @@ -2691,6 +2718,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -3049,6 +3097,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -3484,6 +3533,7 @@ "InterconnectRemoteLocationPermittedConnections", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -3664,6 +3714,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -3859,6 +3910,7 @@ "ProjectsListXpnHostsRequest", "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", + "ProjectView", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", "PublicAdvertisedPrefixPublicDelegatedPrefix", diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 05f5fc39f3a1..56ed0733a80a 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -81,6 +81,7 @@ "google.cloud.compute_v1.services.organization_security_policies", "google.cloud.compute_v1.services.packet_mirrorings", "google.cloud.compute_v1.services.preview_features", + "google.cloud.compute_v1.services.project_views", "google.cloud.compute_v1.services.projects", "google.cloud.compute_v1.services.public_advertised_prefixes", "google.cloud.compute_v1.services.public_delegated_prefixes", @@ -214,6 +215,7 @@ from .services.organization_security_policies import OrganizationSecurityPoliciesClient from .services.packet_mirrorings import PacketMirroringsClient from .services.preview_features import PreviewFeaturesClient +from .services.project_views import ProjectViewsClient from .services.projects import ProjectsClient from .services.public_advertised_prefixes import PublicAdvertisedPrefixesClient from .services.public_delegated_prefixes import PublicDelegatedPrefixesClient @@ -498,6 +500,27 @@ CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, + CapacityAdviceRequest, + CapacityAdviceRequestDistributionPolicy, + CapacityAdviceRequestDistributionPolicyZoneConfiguration, + CapacityAdviceRequestInstanceFlexibilityPolicy, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk, + CapacityAdviceRequestInstanceProperties, + CapacityAdviceRequestInstancePropertiesScheduling, + CapacityAdviceResponse, + CapacityAdviceResponseRecommendation, + CapacityAdviceResponseRecommendationScores, + CapacityAdviceResponseRecommendationShard, + CapacityAdviceRpcRequest, + CapacityHistoryAdviceRequest, + CapacityHistoryRequest, + CapacityHistoryRequestInstanceProperties, + CapacityHistoryRequestInstancePropertiesScheduling, + CapacityHistoryRequestLocationPolicy, + CapacityHistoryResponse, + CapacityHistoryResponsePreemptionRecord, + CapacityHistoryResponsePriceRecord, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -856,6 +879,7 @@ GetPacketMirroringRuleNetworkFirewallPolicyRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -1291,6 +1315,7 @@ InterconnectRemoteLocationPermittedConnections, InterconnectsGetDiagnosticsResponse, InterconnectsGetMacsecConfigResponse, + Interval, InvalidateCacheUrlMapRequest, Items, License, @@ -1471,6 +1496,7 @@ Metadata, MetadataFilter, MetadataFilterLabelMatch, + Money, MoveAddressRequest, MoveDiskProjectRequest, MoveFirewallPolicyRequest, @@ -1666,6 +1692,7 @@ ProjectsListXpnHostsRequest, ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -2553,6 +2580,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -2921,6 +2969,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -3379,6 +3428,7 @@ "InterconnectsClient", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -3563,6 +3613,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -3764,6 +3815,8 @@ "PreviewFeaturesClient", "PreviewRouterRequest", "Project", + "ProjectView", + "ProjectViewsClient", "ProjectsClient", "ProjectsDisableXpnResourceRequest", "ProjectsEnableXpnResourceRequest", diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json index 3d690307220f..85d4758279d6 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json @@ -87,6 +87,16 @@ "methods": [ "calendar_mode" ] + }, + "Capacity": { + "methods": [ + "capacity" + ] + }, + "CapacityHistory": { + "methods": [ + "capacity_history" + ] } } } @@ -2880,6 +2890,20 @@ } } }, + "ProjectViews": { + "clients": { + "rest": { + "libraryClient": "ProjectViewsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + } + } + } + } + }, "Projects": { "clients": { "rest": { diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py index 0b93d44c67cc..74f0493fad1b 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/client.py @@ -707,6 +707,272 @@ def sample_calendar_mode(): # Done; return the response. return response + def capacity( + self, + request: Optional[Union[compute.CapacityAdviceRpcRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + capacity_advice_request_resource: Optional[ + compute.CapacityAdviceRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityAdviceResponse: + r"""Advice on making real-time decisions (such as + choosing zone or machine types) during deployment to + maximize your chances of obtaining capacity. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_capacity(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityAdviceRpcRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CapacityAdviceRpcRequest, dict]): + The request object. A request message for + Advice.Capacity. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + capacity_advice_request_resource (google.cloud.compute_v1.types.CapacityAdviceRequest): + The body resource for this request + This corresponds to the ``capacity_advice_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.CapacityAdviceResponse: + A response contains scoring + recommendations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, region, capacity_advice_request_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CapacityAdviceRpcRequest): + request = compute.CapacityAdviceRpcRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if capacity_advice_request_resource is not None: + request.capacity_advice_request_resource = ( + capacity_advice_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.capacity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def capacity_history( + self, + request: Optional[Union[compute.CapacityHistoryAdviceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + capacity_history_request_resource: Optional[ + compute.CapacityHistoryRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityHistoryResponse: + r"""Gets the capacity history. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_capacity_history(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityHistoryAdviceRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity_history(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CapacityHistoryAdviceRequest, dict]): + The request object. A request message for + Advice.CapacityHistory. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + capacity_history_request_resource (google.cloud.compute_v1.types.CapacityHistoryRequest): + The body resource for this request + This corresponds to the ``capacity_history_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.CapacityHistoryResponse: + Contains the capacity history. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, region, capacity_history_request_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CapacityHistoryAdviceRequest): + request = compute.CapacityHistoryAdviceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if capacity_history_request_resource is not None: + request.capacity_history_request_resource = ( + capacity_history_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.capacity_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "AdviceClient": return self diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py index e4572717cb0b..d4e15a35b9da 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/base.py @@ -148,6 +148,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.capacity: gapic_v1.method.wrap_method( + self.capacity, + default_timeout=600.0, + client_info=client_info, + ), + self.capacity_history: gapic_v1.method.wrap_method( + self.capacity_history, + default_timeout=600.0, + client_info=client_info, + ), } def close(self): @@ -171,6 +181,28 @@ def calendar_mode( ]: raise NotImplementedError() + @property + def capacity( + self, + ) -> Callable[ + [compute.CapacityAdviceRpcRequest], + Union[ + compute.CapacityAdviceResponse, Awaitable[compute.CapacityAdviceResponse] + ], + ]: + raise NotImplementedError() + + @property + def capacity_history( + self, + ) -> Callable[ + [compute.CapacityHistoryAdviceRequest], + Union[ + compute.CapacityHistoryResponse, Awaitable[compute.CapacityHistoryResponse] + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py index 5f6f1c2c010e..1c14e9771201 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest.py @@ -80,6 +80,22 @@ def post_calendar_mode(self, response): logging.log(f"Received response: {response}") return response + def pre_capacity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_capacity(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_capacity_history(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_capacity_history(self, response): + logging.log(f"Received response: {response}") + return response + transport = AdviceRestTransport(interceptor=MyCustomAdviceInterceptor()) client = AdviceClient(transport=transport) @@ -136,6 +152,104 @@ def post_calendar_mode_with_metadata( """ return response, metadata + def pre_capacity( + self, + request: compute.CapacityAdviceRpcRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CapacityAdviceRpcRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for capacity + + Override in a subclass to manipulate the request or metadata + before they are sent to the Advice server. + """ + return request, metadata + + def post_capacity( + self, response: compute.CapacityAdviceResponse + ) -> compute.CapacityAdviceResponse: + """Post-rpc interceptor for capacity + + DEPRECATED. Please use the `post_capacity_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Advice server but before + it is returned to user code. This `post_capacity` interceptor runs + before the `post_capacity_with_metadata` interceptor. + """ + return response + + def post_capacity_with_metadata( + self, + response: compute.CapacityAdviceResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.CapacityAdviceResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for capacity + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Advice server but before it is returned to user code. + + We recommend only using this `post_capacity_with_metadata` + interceptor in new development instead of the `post_capacity` interceptor. + When both interceptors are used, this `post_capacity_with_metadata` interceptor runs after the + `post_capacity` interceptor. The (possibly modified) response returned by + `post_capacity` will be passed to + `post_capacity_with_metadata`. + """ + return response, metadata + + def pre_capacity_history( + self, + request: compute.CapacityHistoryAdviceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CapacityHistoryAdviceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for capacity_history + + Override in a subclass to manipulate the request or metadata + before they are sent to the Advice server. + """ + return request, metadata + + def post_capacity_history( + self, response: compute.CapacityHistoryResponse + ) -> compute.CapacityHistoryResponse: + """Post-rpc interceptor for capacity_history + + DEPRECATED. Please use the `post_capacity_history_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Advice server but before + it is returned to user code. This `post_capacity_history` interceptor runs + before the `post_capacity_history_with_metadata` interceptor. + """ + return response + + def post_capacity_history_with_metadata( + self, + response: compute.CapacityHistoryResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CapacityHistoryResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for capacity_history + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Advice server but before it is returned to user code. + + We recommend only using this `post_capacity_history_with_metadata` + interceptor in new development instead of the `post_capacity_history` interceptor. + When both interceptors are used, this `post_capacity_history_with_metadata` interceptor runs after the + `post_capacity_history` interceptor. The (possibly modified) response returned by + `post_capacity_history` will be passed to + `post_capacity_history_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class AdviceRestStub: @@ -389,6 +503,304 @@ def __call__( ) return resp + class _Capacity(_BaseAdviceRestTransport._BaseCapacity, AdviceRestStub): + def __hash__(self): + return hash("AdviceRestTransport.Capacity") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.CapacityAdviceRpcRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityAdviceResponse: + r"""Call the capacity method over HTTP. + + Args: + request (~.compute.CapacityAdviceRpcRequest): + The request object. A request message for + Advice.Capacity. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.CapacityAdviceResponse: + A response contains scoring + recommendations. + + """ + + http_options = _BaseAdviceRestTransport._BaseCapacity._get_http_options() + request, metadata = self._interceptor.pre_capacity(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAdviceRestTransport._BaseCapacity, + "_BaseCapacity__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.AdviceClient.Capacity", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "Capacity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdviceRestTransport._Capacity._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.CapacityAdviceResponse() + pb_resp = compute.CapacityAdviceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_capacity(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_capacity_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.CapacityAdviceResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.AdviceClient.capacity", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "Capacity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CapacityHistory( + _BaseAdviceRestTransport._BaseCapacityHistory, AdviceRestStub + ): + def __hash__(self): + return hash("AdviceRestTransport.CapacityHistory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.CapacityHistoryAdviceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.CapacityHistoryResponse: + r"""Call the capacity history method over HTTP. + + Args: + request (~.compute.CapacityHistoryAdviceRequest): + The request object. A request message for + Advice.CapacityHistory. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.CapacityHistoryResponse: + Contains the capacity history. + """ + + http_options = ( + _BaseAdviceRestTransport._BaseCapacityHistory._get_http_options() + ) + request, metadata = self._interceptor.pre_capacity_history( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAdviceRestTransport._BaseCapacityHistory, + "_BaseCapacityHistory__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.AdviceClient.CapacityHistory", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "CapacityHistory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdviceRestTransport._CapacityHistory._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.CapacityHistoryResponse() + pb_resp = compute.CapacityHistoryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_capacity_history(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_capacity_history_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.CapacityHistoryResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.AdviceClient.capacity_history", + extra={ + "serviceName": "google.cloud.compute.v1.Advice", + "rpcName": "CapacityHistory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def calendar_mode( self, @@ -399,6 +811,24 @@ def calendar_mode( # In C++ this would require a dynamic_cast return self._CalendarMode(self._session, self._host, self._interceptor) # type: ignore + @property + def capacity( + self, + ) -> Callable[[compute.CapacityAdviceRpcRequest], compute.CapacityAdviceResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Capacity(self._session, self._host, self._interceptor) # type: ignore + + @property + def capacity_history( + self, + ) -> Callable[ + [compute.CapacityHistoryAdviceRequest], compute.CapacityHistoryResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CapacityHistory(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py index 8f470cba5b2c..158fe0974650 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/advice/transports/rest_base.py @@ -104,5 +104,39 @@ def _get_http_options(): ] return http_options + class _BaseCapacity: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/advice/capacity", + "body": "capacity_advice_request_resource", + }, + ] + return http_options + + class _BaseCapacityHistory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/advice/capacityHistory", + "body": "capacity_history_request_resource", + }, + ] + return http_options + __all__ = ("_BaseAdviceRestTransport",) diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/__init__.py new file mode 100644 index 000000000000..6be82c91e927 --- /dev/null +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProjectViewsClient + +__all__ = ("ProjectViewsClient",) diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/client.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/client.py new file mode 100644 index 000000000000..e8b9f2faf1ac --- /dev/null +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/client.py @@ -0,0 +1,723 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, ProjectViewsTransport +from .transports.rest import ProjectViewsRestTransport + + +class ProjectViewsClientMeta(type): + """Metaclass for the ProjectViews client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ProjectViewsTransport]] + _transport_registry["rest"] = ProjectViewsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ProjectViewsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ProjectViewsClient(metaclass=ProjectViewsClientMeta): + """The ProjectViews API.""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProjectViewsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProjectViewsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ProjectViewsTransport: + """Returns the transport used by the client instance. + + Returns: + ProjectViewsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ProjectViewsTransport, Callable[..., ProjectViewsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the project views client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ProjectViewsTransport,Callable[..., ProjectViewsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ProjectViewsTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = ProjectViewsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=ProjectViewsClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ProjectViewsTransport) + if transport_provided: + # transport is a ProjectViewsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(ProjectViewsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=ProjectViewsClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=ProjectViewsClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[ProjectViewsTransport], Callable[..., ProjectViewsTransport] + ] = ( + ProjectViewsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ProjectViewsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.compute_v1.ProjectViewsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1.ProjectViews", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.compute.v1.ProjectViews", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetProjectViewRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ProjectView: + r"""Returns the specified global ProjectViews resource, with a + regional context. This regional API endpoint reads resource + metadata from regional read-only replicas. Because changes are + copied to these regional replicas asynchronously, for real-time + resource reads or any write operations (creating, updating, or + deleting resources), use the global + `projects.get `__ + endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get(): + # Create a client + client = compute_v1.ProjectViewsClient() + + # Initialize request argument(s) + request = compute_v1.GetProjectViewRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetProjectViewRequest, dict]): + The request object. A request message for + ProjectViews.Get. See the method + description for details. + project (str): + Required. Project ID for this + request. This is part of the URL path. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Required. Name of the region for this + request. This is part of the URL path. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.ProjectView: + Represents a ProjectView resource. + + A ProjectView resource contains + read-only project data which is + available globally. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, region] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetProjectViewRequest): + request = compute.GetProjectViewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ProjectViewsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ProjectViewsClient",) diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/README.rst b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/README.rst new file mode 100644 index 000000000000..fb7baaad14ee --- /dev/null +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``ProjectViewsTransport`` is the ABC for all transports. + +- public child ``ProjectViewsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``ProjectViewsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseProjectViewsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``ProjectViewsRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/__init__.py new file mode 100644 index 000000000000..9dcc22fc47ec --- /dev/null +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ProjectViewsTransport +from .rest import ProjectViewsRestInterceptor, ProjectViewsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProjectViewsTransport]] +_transport_registry["rest"] = ProjectViewsRestTransport + +__all__ = ( + "ProjectViewsTransport", + "ProjectViewsRestTransport", + "ProjectViewsRestInterceptor", +) diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/base.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/base.py new file mode 100644 index 000000000000..7442b65c0203 --- /dev/null +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/base.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ProjectViewsTransport(abc.ABC): + """Abstract transport class for ProjectViews.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetProjectViewRequest], + Union[compute.ProjectView, Awaitable[compute.ProjectView]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ProjectViewsTransport",) diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest.py new file mode 100644 index 000000000000..2445e6ddc8d9 --- /dev/null +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1._compat import transcode_request +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProjectViewsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ProjectViewsRestInterceptor: + """Interceptor for ProjectViews. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ProjectViewsRestTransport. + + .. code-block:: python + class MyCustomProjectViewsInterceptor(ProjectViewsRestInterceptor): + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProjectViewsRestTransport(interceptor=MyCustomProjectViewsInterceptor()) + client = ProjectViewsClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetProjectViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetProjectViewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProjectViews server. + """ + return request, metadata + + def post_get(self, response: compute.ProjectView) -> compute.ProjectView: + """Post-rpc interceptor for get + + DEPRECATED. Please use the `post_get_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProjectViews server but before + it is returned to user code. This `post_get` interceptor runs + before the `post_get_with_metadata` interceptor. + """ + return response + + def post_get_with_metadata( + self, + response: compute.ProjectView, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ProjectView, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProjectViews server but before it is returned to user code. + + We recommend only using this `post_get_with_metadata` + interceptor in new development instead of the `post_get` interceptor. + When both interceptors are used, this `post_get_with_metadata` interceptor runs after the + `post_get` interceptor. The (possibly modified) response returned by + `post_get` will be passed to + `post_get_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ProjectViewsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProjectViewsRestInterceptor + + +class ProjectViewsRestTransport(_BaseProjectViewsRestTransport): + """REST backend synchronous transport for ProjectViews. + + The ProjectViews API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ProjectViewsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[ProjectViewsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ProjectViewsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BaseProjectViewsRestTransport._BaseGet, ProjectViewsRestStub): + def __hash__(self): + return hash("ProjectViewsRestTransport.Get") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetProjectViewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ProjectView: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetProjectViewRequest): + The request object. A request message for + ProjectViews.Get. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.ProjectView: + Represents a ProjectView resource. + + A ProjectView resource contains + read-only project data which is + available globally. + + """ + + http_options = _BaseProjectViewsRestTransport._BaseGet._get_http_options() + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseProjectViewsRestTransport._BaseGet, + "_BaseGet__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.ProjectViewsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1.ProjectViews", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProjectViewsRestTransport._Get._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.ProjectView() + pb_resp = compute.ProjectView.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.ProjectView.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.ProjectViewsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1.ProjectViews", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get(self) -> Callable[[compute.GetProjectViewRequest], compute.ProjectView]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ProjectViewsRestTransport",) diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest_base.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest_base.py new file mode 100644 index 000000000000..12259bfb076c --- /dev/null +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/project_views/transports/rest_base.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO, ProjectViewsTransport + + +class _BaseProjectViewsRestTransport(ProjectViewsTransport): + """Base REST backend transport for ProjectViews. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/regions/{region}/projectViews", + }, + ] + return http_options + + +__all__ = ("_BaseProjectViewsRestTransport",) diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py index 6d4b6c14d354..7e744dbe7af6 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py @@ -221,6 +221,27 @@ CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, + CapacityAdviceRequest, + CapacityAdviceRequestDistributionPolicy, + CapacityAdviceRequestDistributionPolicyZoneConfiguration, + CapacityAdviceRequestInstanceFlexibilityPolicy, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection, + CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk, + CapacityAdviceRequestInstanceProperties, + CapacityAdviceRequestInstancePropertiesScheduling, + CapacityAdviceResponse, + CapacityAdviceResponseRecommendation, + CapacityAdviceResponseRecommendationScores, + CapacityAdviceResponseRecommendationShard, + CapacityAdviceRpcRequest, + CapacityHistoryAdviceRequest, + CapacityHistoryRequest, + CapacityHistoryRequestInstanceProperties, + CapacityHistoryRequestInstancePropertiesScheduling, + CapacityHistoryRequestLocationPolicy, + CapacityHistoryResponse, + CapacityHistoryResponsePreemptionRecord, + CapacityHistoryResponsePriceRecord, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -579,6 +600,7 @@ GetPacketMirroringRuleNetworkFirewallPolicyRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -1014,6 +1036,7 @@ InterconnectRemoteLocationPermittedConnections, InterconnectsGetDiagnosticsResponse, InterconnectsGetMacsecConfigResponse, + Interval, InvalidateCacheUrlMapRequest, Items, License, @@ -1194,6 +1217,7 @@ Metadata, MetadataFilter, MetadataFilterLabelMatch, + Money, MoveAddressRequest, MoveDiskProjectRequest, MoveFirewallPolicyRequest, @@ -1389,6 +1413,7 @@ ProjectsListXpnHostsRequest, ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -2270,6 +2295,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -2628,6 +2674,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -3063,6 +3110,7 @@ "InterconnectRemoteLocationPermittedConnections", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -3243,6 +3291,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -3438,6 +3487,7 @@ "ProjectsListXpnHostsRequest", "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", + "ProjectView", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", "PublicAdvertisedPrefixPublicDelegatedPrefix", diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py index 11d8fc30e5f6..c02a7943c5d9 100644 --- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py +++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py @@ -230,6 +230,27 @@ "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", + "CapacityAdviceRequest", + "CapacityAdviceRequestDistributionPolicy", + "CapacityAdviceRequestDistributionPolicyZoneConfiguration", + "CapacityAdviceRequestInstanceFlexibilityPolicy", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + "CapacityAdviceRequestInstanceProperties", + "CapacityAdviceRequestInstancePropertiesScheduling", + "CapacityAdviceResponse", + "CapacityAdviceResponseRecommendation", + "CapacityAdviceResponseRecommendationScores", + "CapacityAdviceResponseRecommendationShard", + "CapacityAdviceRpcRequest", + "CapacityHistoryAdviceRequest", + "CapacityHistoryRequest", + "CapacityHistoryRequestInstanceProperties", + "CapacityHistoryRequestInstancePropertiesScheduling", + "CapacityHistoryRequestLocationPolicy", + "CapacityHistoryResponse", + "CapacityHistoryResponsePreemptionRecord", + "CapacityHistoryResponsePriceRecord", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -590,6 +611,7 @@ "GetPacketMirroringRuleNetworkFirewallPolicyRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -1023,6 +1045,7 @@ "InterconnectRemoteLocationPermittedConnections", "InterconnectsGetDiagnosticsResponse", "InterconnectsGetMacsecConfigResponse", + "Interval", "InvalidateCacheUrlMapRequest", "Items", "License", @@ -1203,6 +1226,7 @@ "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", + "Money", "MoveAddressRequest", "MoveDiskProjectRequest", "MoveFirewallPolicyRequest", @@ -1392,6 +1416,7 @@ "PreviewFeatureStatusReleaseStatus", "PreviewRouterRequest", "Project", + "ProjectView", "ProjectsDisableXpnResourceRequest", "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", @@ -22258,10 +22283,11 @@ class BackendServiceHAPolicyLeaderNetworkEndpoint(proto.Message): attached to the NEG specified in the haPolicy.leader.backendGroup. - The name must be 1-63 characters long, and - comply with RFC1035. Authorization requires the - following IAM permission on the specified - resource instance: compute.instances.use + The value must be a valid RFC1035 name (1-63 + characters) or a valid instance URL. + Authorization requires the following IAM + permission on the specified resource instance: + compute.instances.use This field is a member of `oneof`_ ``_instance``. """ @@ -25657,6 +25683,819 @@ class CancelRolloutRequest(proto.Message): ) +class CapacityAdviceRequest(proto.Message): + r"""A request to provide Assistant Scores. These scores determine + VM obtainability and preemption likelihood. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + distribution_policy (google.cloud.compute_v1.types.CapacityAdviceRequestDistributionPolicy): + Policy specifying the distribution of + instances across zones within the requested + region. + + This field is a member of `oneof`_ ``_distribution_policy``. + instance_flexibility_policy (google.cloud.compute_v1.types.CapacityAdviceRequestInstanceFlexibilityPolicy): + Policy for instance selectors. + + This field is a member of `oneof`_ ``_instance_flexibility_policy``. + instance_properties (google.cloud.compute_v1.types.CapacityAdviceRequestInstanceProperties): + Instance properties for this request. + + This field is a member of `oneof`_ ``_instance_properties``. + size (int): + The number of VM instances to request. + + This field is a member of `oneof`_ ``_size``. + """ + + distribution_policy: "CapacityAdviceRequestDistributionPolicy" = proto.Field( + proto.MESSAGE, + number=534558541, + optional=True, + message="CapacityAdviceRequestDistributionPolicy", + ) + instance_flexibility_policy: "CapacityAdviceRequestInstanceFlexibilityPolicy" = ( + proto.Field( + proto.MESSAGE, + number=26937090, + optional=True, + message="CapacityAdviceRequestInstanceFlexibilityPolicy", + ) + ) + instance_properties: "CapacityAdviceRequestInstanceProperties" = proto.Field( + proto.MESSAGE, + number=215355165, + optional=True, + message="CapacityAdviceRequestInstanceProperties", + ) + size: int = proto.Field( + proto.INT32, + number=3530753, + optional=True, + ) + + +class CapacityAdviceRequestDistributionPolicy(proto.Message): + r"""Distribution policy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + target_shape (str): + Target distribution shape. You can specify the following + values:ANY, ANY_SINGLE_ZONE, or BALANCED. Check the + TargetShape enum for the list of possible values. + + This field is a member of `oneof`_ ``_target_shape``. + zones (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceRequestDistributionPolicyZoneConfiguration]): + Zones where Capacity Advisor looks for + capacity. + """ + + class TargetShape(proto.Enum): + r"""Target distribution shape. You can specify the following values:ANY, + ANY_SINGLE_ZONE, or BALANCED. + + Values: + UNDEFINED_TARGET_SHAPE (0): + A value indicating that the enum field is not + set. + ANY (64972): + Picks zones for creating VM instances to + fulfill the requested number of VMs within + present resource constraints. + ANY_SINGLE_ZONE (61100880): + Creates all VM instances within a single + zone. The zone is selected based on the present + resource constraints. + BALANCED (468409608): + Prioritizes acquisition of resources, + scheduling VMs in zones where resources are + available while distributing VMs as evenly as + possible across selected zones to minimize the + impact of zonal failure. + TARGET_SHAPE_UNSPECIFIED (449316907): + Default value, unused. + """ + + UNDEFINED_TARGET_SHAPE = 0 + ANY = 64972 + ANY_SINGLE_ZONE = 61100880 + BALANCED = 468409608 + TARGET_SHAPE_UNSPECIFIED = 449316907 + + target_shape: str = proto.Field( + proto.STRING, + number=338621299, + optional=True, + ) + zones: MutableSequence[ + "CapacityAdviceRequestDistributionPolicyZoneConfiguration" + ] = proto.RepeatedField( + proto.MESSAGE, + number=116085319, + message="CapacityAdviceRequestDistributionPolicyZoneConfiguration", + ) + + +class CapacityAdviceRequestDistributionPolicyZoneConfiguration(proto.Message): + r"""Zone configuration for the distribution policy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + zone (str): + The URL of the zone. It can be a + partial or full URL. For example, the following + are valid values: + + + - + https://www.googleapis.com/compute/v1/projects/project/zones/zone + - projects/project/zones/zone + - zones/zone + + This field is a member of `oneof`_ ``_zone``. + """ + + zone: str = proto.Field( + proto.STRING, + number=3744684, + optional=True, + ) + + +class CapacityAdviceRequestInstanceFlexibilityPolicy(proto.Message): + r"""Specification of alternative, flexible instance + configurations. + + Attributes: + instance_selections (MutableMapping[str, google.cloud.compute_v1.types.CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection]): + Named instance selections to configure + properties. The key is an arbitrary, unique + RFC1035 string that identifies the instance + selection. + """ + + instance_selections: MutableMapping[ + str, "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=22954577, + message="CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection", + ) + + +class CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelection(proto.Message): + r"""Machine specification. + + Attributes: + disks (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk]): + Local SSDs. + guest_accelerators (MutableSequence[google.cloud.compute_v1.types.AcceleratorConfig]): + Accelerators configuration. + machine_types (MutableSequence[str]): + Full machine-type names, e.g. + "n1-standard-16". + """ + + disks: MutableSequence[ + "CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk" + ] = proto.RepeatedField( + proto.MESSAGE, + number=95594102, + message="CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk", + ) + guest_accelerators: MutableSequence["AcceleratorConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=463595119, + message="AcceleratorConfig", + ) + machine_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=79720065, + ) + + +class CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDisk( + proto.Message +): + r"""Attached disk configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (str): + Specifies the type of the disk. + Check the Type enum for the list of possible + values. + + This field is a member of `oneof`_ ``_type``. + """ + + class Type(proto.Enum): + r"""Specifies the type of the disk. + + Values: + UNDEFINED_TYPE (0): + A value indicating that the enum field is not + set. + DISK_TYPE_UNSPECIFIED (333621236): + Default value, unspecified disk type. + SCRATCH (496778970): + Scratch disk (Local SSD). + """ + + UNDEFINED_TYPE = 0 + DISK_TYPE_UNSPECIFIED = 333621236 + SCRATCH = 496778970 + + type_: str = proto.Field( + proto.STRING, + number=3575610, + optional=True, + ) + + +class CapacityAdviceRequestInstanceProperties(proto.Message): + r"""Instance provisioning properties. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scheduling (google.cloud.compute_v1.types.CapacityAdviceRequestInstancePropertiesScheduling): + Specifies the scheduling options. + + This field is a member of `oneof`_ ``_scheduling``. + """ + + scheduling: "CapacityAdviceRequestInstancePropertiesScheduling" = proto.Field( + proto.MESSAGE, + number=386688404, + optional=True, + message="CapacityAdviceRequestInstancePropertiesScheduling", + ) + + +class CapacityAdviceRequestInstancePropertiesScheduling(proto.Message): + r"""Defines the instance scheduling options. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + provisioning_model (str): + Specifies the provisioning model. + Check the ProvisioningModel enum for the list of + possible values. + + This field is a member of `oneof`_ ``_provisioning_model``. + """ + + class ProvisioningModel(proto.Enum): + r"""Specifies the provisioning model. + + Values: + UNDEFINED_PROVISIONING_MODEL (0): + A value indicating that the enum field is not + set. + FLEX_START (101746812): + Instance is provisioned using the Flex Start + provisioning model and has a limited runtime. + RESERVATION_BOUND (293538571): + Bound to the lifecycle of the reservation in + which it is provisioned. + SPOT (2552066): + Heavily discounted, no guaranteed runtime. + STANDARD (484642493): + Standard provisioning with user controlled + runtime, no discounts. + """ + + UNDEFINED_PROVISIONING_MODEL = 0 + FLEX_START = 101746812 + RESERVATION_BOUND = 293538571 + SPOT = 2552066 + STANDARD = 484642493 + + provisioning_model: str = proto.Field( + proto.STRING, + number=494423, + optional=True, + ) + + +class CapacityAdviceResponse(proto.Message): + r"""A response contains scoring recommendations. + + Attributes: + recommendations (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceResponseRecommendation]): + Initially the API will provide one + recommendation which balances the individual + scores according to the service provider's + preference. + """ + + recommendations: MutableSequence["CapacityAdviceResponseRecommendation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=324515802, + message="CapacityAdviceResponseRecommendation", + ) + ) + + +class CapacityAdviceResponseRecommendation(proto.Message): + r"""Recommendation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scores (google.cloud.compute_v1.types.CapacityAdviceResponseRecommendationScores): + Scores for the recommendation. + + This field is a member of `oneof`_ ``_scores``. + shards (MutableSequence[google.cloud.compute_v1.types.CapacityAdviceResponseRecommendationShard]): + Shards represent blocks of uniform capacity + in recommendations. + """ + + scores: "CapacityAdviceResponseRecommendationScores" = proto.Field( + proto.MESSAGE, + number=165975073, + optional=True, + message="CapacityAdviceResponseRecommendationScores", + ) + shards: MutableSequence["CapacityAdviceResponseRecommendationShard"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=170175573, + message="CapacityAdviceResponseRecommendationShard", + ) + ) + + +class CapacityAdviceResponseRecommendationScores(proto.Message): + r"""Groups information about a shard of capacity. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + estimated_uptime (str): + The estimated run time of the majority of + Spot VMs in the request before preemption. The + estimate is best-effort only. It is based on + historical data and current conditions. + + This field is a member of `oneof`_ ``_estimated_uptime``. + obtainability (float): + The obtainability score indicates the + likelihood of successfully obtaining + (provisioning) the requested number of VMs. The + score range is 0.0 through 1.0. Higher is + better. + + This field is a member of `oneof`_ ``_obtainability``. + """ + + estimated_uptime: str = proto.Field( + proto.STRING, + number=223976779, + optional=True, + ) + obtainability: float = proto.Field( + proto.DOUBLE, + number=260735205, + optional=True, + ) + + +class CapacityAdviceResponseRecommendationShard(proto.Message): + r"""Shards represent blocks of uniform capacity in + recommendations. Each shard is for a single zone and a single + machine shape. Each shard defines a size expressed as the number + of VMs. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_count (int): + The number of instances. + + This field is a member of `oneof`_ ``_instance_count``. + machine_type (str): + The machine type corresponds to the instance + selection in the request. + + This field is a member of `oneof`_ ``_machine_type``. + provisioning_model (str): + The provisioning model that you want to view + recommendations for. Check the ProvisioningModel + enum for the list of possible values. + + This field is a member of `oneof`_ ``_provisioning_model``. + zone (str): + Output only. The zone name for this shard. + + This field is a member of `oneof`_ ``_zone``. + """ + + class ProvisioningModel(proto.Enum): + r"""The provisioning model that you want to view recommendations + for. + + Values: + UNDEFINED_PROVISIONING_MODEL (0): + A value indicating that the enum field is not + set. + FLEX_START (101746812): + Instance is provisioned using the Flex Start + provisioning model and has a limited runtime. + RESERVATION_BOUND (293538571): + Bound to the lifecycle of the reservation in + which it is provisioned. + SPOT (2552066): + Heavily discounted, no guaranteed runtime. + STANDARD (484642493): + Standard provisioning with user controlled + runtime, no discounts. + """ + + UNDEFINED_PROVISIONING_MODEL = 0 + FLEX_START = 101746812 + RESERVATION_BOUND = 293538571 + SPOT = 2552066 + STANDARD = 484642493 + + instance_count: int = proto.Field( + proto.INT32, + number=77317349, + optional=True, + ) + machine_type: str = proto.Field( + proto.STRING, + number=227711026, + optional=True, + ) + provisioning_model: str = proto.Field( + proto.STRING, + number=494423, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + optional=True, + ) + + +class CapacityAdviceRpcRequest(proto.Message): + r"""A request message for Advice.Capacity. See the method + description for details. + + Attributes: + capacity_advice_request_resource (google.cloud.compute_v1.types.CapacityAdviceRequest): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + """ + + capacity_advice_request_resource: "CapacityAdviceRequest" = proto.Field( + proto.MESSAGE, + number=176354208, + message="CapacityAdviceRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + +class CapacityHistoryAdviceRequest(proto.Message): + r"""A request message for Advice.CapacityHistory. See the method + description for details. + + Attributes: + capacity_history_request_resource (google.cloud.compute_v1.types.CapacityHistoryRequest): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + """ + + capacity_history_request_resource: "CapacityHistoryRequest" = proto.Field( + proto.MESSAGE, + number=182030318, + message="CapacityHistoryRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + +class CapacityHistoryRequest(proto.Message): + r"""A request to get the capacity history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_properties (google.cloud.compute_v1.types.CapacityHistoryRequestInstanceProperties): + Instance properties for this request. + + This field is a member of `oneof`_ ``_instance_properties``. + location_policy (google.cloud.compute_v1.types.CapacityHistoryRequestLocationPolicy): + Location policy for this request. + + This field is a member of `oneof`_ ``_location_policy``. + types (MutableSequence[str]): + List of history types to get capacity history + for. Check the Types enum for the list of + possible values. + """ + + class Types(proto.Enum): + r""" + + Values: + UNDEFINED_TYPES (0): + A value indicating that the enum field is not + set. + HISTORY_TYPE_UNSPECIFIED (58549757): + Default value, unused. + PREEMPTION (512869337): + Preemption history. + PRICE (76396841): + Price history. + """ + + UNDEFINED_TYPES = 0 + HISTORY_TYPE_UNSPECIFIED = 58549757 + PREEMPTION = 512869337 + PRICE = 76396841 + + instance_properties: "CapacityHistoryRequestInstanceProperties" = proto.Field( + proto.MESSAGE, + number=215355165, + optional=True, + message="CapacityHistoryRequestInstanceProperties", + ) + location_policy: "CapacityHistoryRequestLocationPolicy" = proto.Field( + proto.MESSAGE, + number=465689852, + optional=True, + message="CapacityHistoryRequestLocationPolicy", + ) + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=110844025, + ) + + +class CapacityHistoryRequestInstanceProperties(proto.Message): + r"""Instance properties for this request. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + machine_type (str): + The machine type for the VM, such as ``n2-standard-4``. + + This field is a member of `oneof`_ ``_machine_type``. + scheduling (google.cloud.compute_v1.types.CapacityHistoryRequestInstancePropertiesScheduling): + Specifies the scheduling options. + + This field is a member of `oneof`_ ``_scheduling``. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=227711026, + optional=True, + ) + scheduling: "CapacityHistoryRequestInstancePropertiesScheduling" = proto.Field( + proto.MESSAGE, + number=386688404, + optional=True, + message="CapacityHistoryRequestInstancePropertiesScheduling", + ) + + +class CapacityHistoryRequestInstancePropertiesScheduling(proto.Message): + r"""Scheduling options. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + provisioning_model (str): + The provisioning model to get capacity + history for. This field must be set to SPOT. + + For more information, see + Compute Engine instances provisioning models. + Check the ProvisioningModel enum for the list of + possible values. + + This field is a member of `oneof`_ ``_provisioning_model``. + """ + + class ProvisioningModel(proto.Enum): + r"""The provisioning model to get capacity history for. + This field must be set to SPOT. + + For more information, see + Compute Engine instances provisioning models. + + Values: + UNDEFINED_PROVISIONING_MODEL (0): + A value indicating that the enum field is not + set. + FLEX_START (101746812): + Instance is provisioned using the Flex Start + provisioning model and has a limited runtime. + RESERVATION_BOUND (293538571): + Bound to the lifecycle of the reservation in + which it is provisioned. + SPOT (2552066): + Heavily discounted, no guaranteed runtime. + STANDARD (484642493): + Standard provisioning with user controlled + runtime, no discounts. + """ + + UNDEFINED_PROVISIONING_MODEL = 0 + FLEX_START = 101746812 + RESERVATION_BOUND = 293538571 + SPOT = 2552066 + STANDARD = 484642493 + + provisioning_model: str = proto.Field( + proto.STRING, + number=494423, + optional=True, + ) + + +class CapacityHistoryRequestLocationPolicy(proto.Message): + r"""Location policy for this request. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (str): + The region or zone to get capacity history + for. + It can be a partial or full URL. For example, + the following are valid values: + + + - + https://www.googleapis.com/compute/v1/projects/project/zones/zone + - projects/project/zones/zone + - zones/zone + + This field is optional. + + This field is a member of `oneof`_ ``_location``. + """ + + location: str = proto.Field( + proto.STRING, + number=290430901, + optional=True, + ) + + +class CapacityHistoryResponse(proto.Message): + r"""Contains the capacity history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (str): + Output only. The location (region or zone) + for which the capacity history is returned. It + is returned as a URL - For + example,https://www.googleapis.com/compute/v1/projects/project/zones/zone. + + This field is a member of `oneof`_ ``_location``. + machine_type (str): + The machine type for which the capacity + history is returned. + + This field is a member of `oneof`_ ``_machine_type``. + preemption_history (MutableSequence[google.cloud.compute_v1.types.CapacityHistoryResponsePreemptionRecord]): + The preemption history for the requested + machine type and location. + price_history (MutableSequence[google.cloud.compute_v1.types.CapacityHistoryResponsePriceRecord]): + The price history for the requested machine + type and location. + """ + + location: str = proto.Field( + proto.STRING, + number=290430901, + optional=True, + ) + machine_type: str = proto.Field( + proto.STRING, + number=227711026, + optional=True, + ) + preemption_history: MutableSequence["CapacityHistoryResponsePreemptionRecord"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=364018222, + message="CapacityHistoryResponsePreemptionRecord", + ) + ) + price_history: MutableSequence["CapacityHistoryResponsePriceRecord"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=326230942, + message="CapacityHistoryResponsePriceRecord", + ) + ) + + +class CapacityHistoryResponsePreemptionRecord(proto.Message): + r"""A record of Spot VM preemption history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + interval (google.cloud.compute_v1.types.Interval): + The time interval for this preemption record. + + This field is a member of `oneof`_ ``_interval``. + preemption_rate (float): + The preemption rate during the interval, + representing the fraction of Spot VMs that were + preempted. Range: 0.0 to 1.0. Preemption rate is + calculated as (total preempted Spots) / (total + Spots that stopped running). + + This field is a member of `oneof`_ ``_preemption_rate``. + """ + + interval: "Interval" = proto.Field( + proto.MESSAGE, + number=33547461, + optional=True, + message="Interval", + ) + preemption_rate: float = proto.Field( + proto.DOUBLE, + number=140651910, + optional=True, + ) + + +class CapacityHistoryResponsePriceRecord(proto.Message): + r"""A record of price history. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + interval (google.cloud.compute_v1.types.Interval): + The time interval for this price record. + + This field is a member of `oneof`_ ``_interval``. + list_price (google.cloud.compute_v1.types.Money): + The Spot VM list price during the interval. + + This field is a member of `oneof`_ ``_list_price``. + """ + + interval: "Interval" = proto.Field( + proto.MESSAGE, + number=33547461, + optional=True, + message="Interval", + ) + list_price: "Money" = proto.Field( + proto.MESSAGE, + number=167990888, + optional=True, + message="Money", + ) + + class CircuitBreakers(proto.Message): r"""Settings controlling the volume of requests, connections and retries to this backend service. @@ -26117,12 +26956,14 @@ class Commitment(proto.Message): GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, - STORAGE_OPTIMIZED_Z3. For example, type MEMORY_OPTIMIZED - specifies a commitment that applies only to eligible - resources of memory optimized M1 and M2 machine series. Type - GENERAL_PURPOSE specifies a commitment that applies only to - eligible resources of general purpose N1 machine series. - Check the Type enum for the list of possible values. + STORAGE_OPTIMIZED_Z3,STORAGE_OPTIMIZED_Z4DS, + STORAGE_OPTIMIZED_Z4DH,STORAGE_OPTIMIZED_Z4D4T. For example, + type MEMORY_OPTIMIZED specifies a commitment that applies + only to eligible resources of memory optimized M1 and M2 + machine series. Type GENERAL_PURPOSE specifies a commitment + that applies only to eligible resources of general purpose + N1 machine series. Check the Type enum for the list of + possible values. This field is a member of `oneof`_ ``_type``. """ @@ -26226,11 +27067,13 @@ class Type(proto.Enum): GENERAL_PURPOSE_N2D,GENERAL_PURPOSE_N4, GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, - MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, STORAGE_OPTIMIZED_Z3. For - example, type MEMORY_OPTIMIZED specifies a commitment that applies - only to eligible resources of memory optimized M1 and M2 machine - series. Type GENERAL_PURPOSE specifies a commitment that applies - only to eligible resources of general purpose N1 machine series. + MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, + STORAGE_OPTIMIZED_Z3,STORAGE_OPTIMIZED_Z4DS, + STORAGE_OPTIMIZED_Z4DH,STORAGE_OPTIMIZED_Z4D4T. For example, type + MEMORY_OPTIMIZED specifies a commitment that applies only to + eligible resources of memory optimized M1 and M2 machine series. + Type GENERAL_PURPOSE specifies a commitment that applies only to + eligible resources of general purpose N1 machine series. Values: UNDEFINED_TYPE (0): @@ -26328,6 +27171,12 @@ class Type(proto.Enum): CUD bucket for NETWORK_OPTIMIZED_U4S machines. STORAGE_OPTIMIZED_Z3 (316796085): No description available. + STORAGE_OPTIMIZED_Z4D4T (18503022): + CUD bucket for Z4D-4T machines. + STORAGE_OPTIMIZED_Z4DH (35233722): + CUD bucket for Z4DH machines. + STORAGE_OPTIMIZED_Z4DS (35233733): + CUD bucket for Z4DS machines. TYPE_UNSPECIFIED (437714322): Note for internal users: When adding a new enum Type for v1, make sure to also add it in the comment for the @@ -26379,6 +27228,9 @@ class Type(proto.Enum): NETWORK_OPTIMIZED_U4P = 147044872 NETWORK_OPTIMIZED_U4S = 147044875 STORAGE_OPTIMIZED_Z3 = 316796085 + STORAGE_OPTIMIZED_Z4D4T = 18503022 + STORAGE_OPTIMIZED_Z4DH = 35233722 + STORAGE_OPTIMIZED_Z4DS = 35233733 TYPE_UNSPECIFIED = 437714322 auto_renew: bool = proto.Field( @@ -46881,6 +47733,29 @@ class GetProjectRequest(proto.Message): ) +class GetProjectViewRequest(proto.Message): + r"""A request message for ProjectViews.Get. See the method + description for details. + + Attributes: + project (str): + Required. Project ID for this request. This + is part of the URL path. + region (str): + Required. Name of the region for this + request. This is part of the URL path. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetPublicAdvertisedPrefixeRequest(proto.Message): r"""A request message for PublicAdvertisedPrefixes.Get. See the method description for details. @@ -50788,6 +51663,9 @@ class Type(proto.Enum): set. BARE_METAL_LINUX_COMPATIBLE (354232740): No description available. + BMSAI_CAPABLE (449302109): + Indicates the guest OS is capable of Bare + Metal Secure AI (BMSAI) confidential computing. CCA_CAPABLE (79012270): No description available. FEATURE_TYPE_UNSPECIFIED (531767259): @@ -50825,6 +51703,7 @@ class Type(proto.Enum): UNDEFINED_TYPE = 0 BARE_METAL_LINUX_COMPATIBLE = 354232740 + BMSAI_CAPABLE = 449302109 CCA_CAPABLE = 79012270 FEATURE_TYPE_UNSPECIFIED = 531767259 GVNIC = 68209305 @@ -66753,7 +67632,15 @@ class InstancePropertiesPatch(proto.Message): r"""Represents the change that you want to make to the instance properties. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: + expose_host_topology (bool): + This optional flag exposes the hashed + physical host ID. + + This field is a member of `oneof`_ ``_expose_host_topology``. labels (MutableMapping[str, str]): The label key-value pairs that you want to patch onto the instance. @@ -66763,6 +67650,11 @@ class InstancePropertiesPatch(proto.Message): see Project and instance metadata. """ + expose_host_topology: bool = proto.Field( + proto.BOOL, + number=428530155, + optional=True, + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -75355,6 +76247,47 @@ class InterconnectsGetMacsecConfigResponse(proto.Message): ) +class Interval(proto.Message): + r"""Represents a time interval, encoded as a Timestamp start + (inclusive) and a Timestamp end (exclusive). + + The start must be less than or equal to the end. + When the start equals the end, the interval is empty (matches no + time). When both start and end are unspecified, the interval + matches any time. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + end_time (str): + Optional. Exclusive end of the interval. + + If specified, a Timestamp matching this interval + will have to be before the end. + + This field is a member of `oneof`_ ``_end_time``. + start_time (str): + Optional. Inclusive start of the interval. + + If specified, a Timestamp matching this interval + will have to be the same or after the start. + + This field is a member of `oneof`_ ``_start_time``. + """ + + end_time: str = proto.Field( + proto.STRING, + number=114938801, + optional=True, + ) + start_time: str = proto.Field( + proto.STRING, + number=37467274, + optional=True, + ) + + class InvalidateCacheUrlMapRequest(proto.Message): r"""A request message for UrlMaps.InvalidateCache. See the method description for details. @@ -101709,6 +102642,51 @@ class MetadataFilterLabelMatch(proto.Message): ) +class Money(proto.Message): + r"""Represents an amount of money with its currency type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + currency_code (str): + The three-letter currency code defined in ISO + 4217. + + This field is a member of `oneof`_ ``_currency_code``. + nanos (int): + Number of nano (10^-9) units of the amount. The value must + be between -999,999,999 and +999,999,999 inclusive. If + ``units`` is positive, ``nanos`` must be positive or zero. + If ``units`` is zero, ``nanos`` can be positive, zero, or + negative. If ``units`` is negative, ``nanos`` must be + negative or zero. For example $-1.75 is represented as + ``units``\ =-1 and ``nanos``\ =-750,000,000. + + This field is a member of `oneof`_ ``_nanos``. + units (int): + The whole units of the amount. For example if + ``currencyCode`` is ``"USD"``, then 1 unit is one US dollar. + + This field is a member of `oneof`_ ``_units``. + """ + + currency_code: str = proto.Field( + proto.STRING, + number=34986331, + optional=True, + ) + nanos: int = proto.Field( + proto.INT32, + number=104586303, + optional=True, + ) + units: int = proto.Field( + proto.INT64, + number=111433583, + optional=True, + ) + + class MoveAddressRequest(proto.Message): r"""A request message for Addresses.Move. See the method description for details. @@ -117225,6 +118203,35 @@ class XpnProjectStatus(proto.Enum): ) +class ProjectView(proto.Message): + r"""Represents a ProjectView resource. + + A ProjectView resource contains read-only project data which is + available globally. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (google.cloud.compute_v1.types.Project): + The project data. The returned Project data does not contain + regional or zonal quota usage data. Global quota limits are + present. For accurate, real-time quota usage numbers, query + the global + `projects.get `__ + endpoint. + + This field is a member of `oneof`_ ``_project``. + """ + + project: "Project" = proto.Field( + proto.MESSAGE, + number=227560217, + optional=True, + message="Project", + ) + + class ProjectsDisableXpnResourceRequest(proto.Message): r""" @@ -133554,6 +134561,12 @@ class Scheduling(proto.Message): attached to the instance. This field is a member of `oneof`_ ``_availability_domain``. + expose_host_topology (bool): + This optional flag exposes the hashed + physical host ID in the ResourceStatus resource + of the VM. + + This field is a member of `oneof`_ ``_expose_host_topology``. graceful_shutdown (google.cloud.compute_v1.types.SchedulingGracefulShutdown): This field is a member of `oneof`_ ``_graceful_shutdown``. @@ -133743,6 +134756,11 @@ class ProvisioningModel(proto.Enum): number=252514344, optional=True, ) + expose_host_topology: bool = proto.Field( + proto.BOOL, + number=428530155, + optional=True, + ) graceful_shutdown: "SchedulingGracefulShutdown" = proto.Field( proto.MESSAGE, number=226325136, diff --git a/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_history_sync.py b/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_history_sync.py new file mode 100644 index 000000000000..54d425faba73 --- /dev/null +++ b/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_history_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CapacityHistory +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Advice_CapacityHistory_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_capacity_history(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityHistoryAdviceRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity_history(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Advice_CapacityHistory_sync] diff --git a/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_sync.py b/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_sync.py new file mode 100644 index 000000000000..0c07e76daf08 --- /dev/null +++ b/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_advice_capacity_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Capacity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Advice_Capacity_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_capacity(): + # Create a client + client = compute_v1.AdviceClient() + + # Initialize request argument(s) + request = compute_v1.CapacityAdviceRpcRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.capacity(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Advice_Capacity_sync] diff --git a/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_project_views_get_sync.py b/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_project_views_get_sync.py new file mode 100644 index 000000000000..f19a30336f0f --- /dev/null +++ b/preview-packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_project_views_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_ProjectViews_Get_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get(): + # Create a client + client = compute_v1.ProjectViewsClient() + + # Initialize request argument(s) + request = compute_v1.GetProjectViewRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_ProjectViews_Get_sync] diff --git a/preview-packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json b/preview-packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json index 654b1b935273..1011bde6bc9c 100644 --- a/preview-packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json +++ b/preview-packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json @@ -1055,6 +1055,182 @@ ], "title": "compute_v1_generated_advice_calendar_mode_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.AdviceClient", + "shortName": "AdviceClient" + }, + "fullName": "google.cloud.compute_v1.AdviceClient.capacity_history", + "method": { + "fullName": "google.cloud.compute.v1.Advice.CapacityHistory", + "service": { + "fullName": "google.cloud.compute.v1.Advice", + "shortName": "Advice" + }, + "shortName": "CapacityHistory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.CapacityHistoryAdviceRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "capacity_history_request_resource", + "type": "google.cloud.compute_v1.types.CapacityHistoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.CapacityHistoryResponse", + "shortName": "capacity_history" + }, + "description": "Sample for CapacityHistory", + "file": "compute_v1_generated_advice_capacity_history_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Advice_CapacityHistory_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_advice_capacity_history_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.AdviceClient", + "shortName": "AdviceClient" + }, + "fullName": "google.cloud.compute_v1.AdviceClient.capacity", + "method": { + "fullName": "google.cloud.compute.v1.Advice.Capacity", + "service": { + "fullName": "google.cloud.compute.v1.Advice", + "shortName": "Advice" + }, + "shortName": "Capacity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.CapacityAdviceRpcRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "capacity_advice_request_resource", + "type": "google.cloud.compute_v1.types.CapacityAdviceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.CapacityAdviceResponse", + "shortName": "capacity" + }, + "description": "Sample for Capacity", + "file": "compute_v1_generated_advice_capacity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Advice_Capacity_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_advice_capacity_sync.py" + }, { "canonical": true, "clientMethod": { @@ -41163,6 +41339,90 @@ ], "title": "compute_v1_generated_preview_features_update_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ProjectViewsClient", + "shortName": "ProjectViewsClient" + }, + "fullName": "google.cloud.compute_v1.ProjectViewsClient.get", + "method": { + "fullName": "google.cloud.compute.v1.ProjectViews.Get", + "service": { + "fullName": "google.cloud.compute.v1.ProjectViews", + "shortName": "ProjectViews" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetProjectViewRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.ProjectView", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_project_views_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_ProjectViews_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_project_views_get_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py index b7e09710dea1..03a997a86080 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_advice.py @@ -1073,90 +1073,874 @@ def test_calendar_mode_rest_flattened_error(transport: str = "rest"): ) +def test_capacity_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.capacity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.capacity] = mock_rpc + + request = {} + client.capacity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.capacity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_capacity_rest_required_fields(request_type=compute.CapacityAdviceRpcRequest): + transport_class = transports.AdviceRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCapacity, + "_BaseCapacity__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.CapacityAdviceResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CapacityAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.capacity(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_capacity_rest_flattened(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CapacityAdviceResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + capacity_advice_request_resource=compute.CapacityAdviceRequest( + distribution_policy=compute.CapacityAdviceRequestDistributionPolicy( + target_shape="target_shape_value" + ) + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.CapacityAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.capacity(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/advice/capacity" + % client.transport._host, + args[1], + ) + + +def test_capacity_rest_flattened_error(transport: str = "rest"): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.capacity( + compute.CapacityAdviceRpcRequest(), + project="project_value", + region="region_value", + capacity_advice_request_resource=compute.CapacityAdviceRequest( + distribution_policy=compute.CapacityAdviceRequestDistributionPolicy( + target_shape="target_shape_value" + ) + ), + ) + + +def test_capacity_history_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.capacity_history in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.capacity_history] = ( + mock_rpc + ) + + request = {} + client.capacity_history(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.capacity_history(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_capacity_history_rest_required_fields( + request_type=compute.CapacityHistoryAdviceRequest, +): + transport_class = transports.AdviceRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCapacityHistory, + "_BaseCapacityHistory__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.CapacityHistoryResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CapacityHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.capacity_history(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_capacity_history_rest_flattened(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CapacityHistoryResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + capacity_history_request_resource=compute.CapacityHistoryRequest( + instance_properties=compute.CapacityHistoryRequestInstanceProperties( + machine_type="machine_type_value" + ) + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.CapacityHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.capacity_history(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/advice/capacityHistory" + % client.transport._host, + args[1], + ) + + +def test_capacity_history_rest_flattened_error(transport: str = "rest"): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.capacity_history( + compute.CapacityHistoryAdviceRequest(), + project="project_value", + region="region_value", + capacity_history_request_resource=compute.CapacityHistoryRequest( + instance_properties=compute.CapacityHistoryRequestInstanceProperties( + machine_type="machine_type_value" + ) + ), + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AdviceRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) - with pytest.raises(ValueError): - client = AdviceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + with pytest.raises(ValueError): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdviceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdviceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdviceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdviceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AdviceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AdviceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = AdviceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_calendar_mode_rest_bad_request( + request_type=compute.CalendarModeAdviceRpcRequest, +): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.calendar_mode(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CalendarModeAdviceRpcRequest, + dict, + ], +) +def test_calendar_mode_rest_call_success(request_type): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["calendar_mode_advice_request_resource"] = { + "future_resources_specs": {} + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.CalendarModeAdviceRpcRequest.meta.fields[ + "calendar_mode_advice_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "calendar_mode_advice_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["calendar_mode_advice_request_resource"][field]) + ): + del request_init["calendar_mode_advice_request_resource"][field][i][ + subfield + ] + else: + del request_init["calendar_mode_advice_request_resource"][field][ + subfield + ] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CalendarModeAdviceResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CalendarModeAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.calendar_mode(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.CalendarModeAdviceResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_calendar_mode_rest_interceptors(null_interceptor): + transport = transports.AdviceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AdviceRestInterceptor(), + ) + client = AdviceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AdviceRestInterceptor, "post_calendar_mode" + ) as post, + mock.patch.object( + transports.AdviceRestInterceptor, "post_calendar_mode_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.AdviceRestInterceptor, "pre_calendar_mode") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CalendarModeAdviceRpcRequest.pb( + compute.CalendarModeAdviceRpcRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.CalendarModeAdviceResponse.to_json( + compute.CalendarModeAdviceResponse() + ) + req.return_value.content = return_value + + request = compute.CalendarModeAdviceRpcRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.CalendarModeAdviceResponse() + post_with_metadata.return_value = compute.CalendarModeAdviceResponse(), metadata + + client.calendar_mode( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_capacity_rest_bad_request(request_type=compute.CapacityAdviceRpcRequest): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.capacity(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CapacityAdviceRpcRequest, + dict, + ], +) +def test_capacity_rest_call_success(request_type): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.AdviceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AdviceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["capacity_advice_request_resource"] = { + "distribution_policy": { + "target_shape": "target_shape_value", + "zones": [{"zone": "zone_value"}], + }, + "instance_flexibility_policy": {"instance_selections": {}}, + "instance_properties": { + "scheduling": {"provisioning_model": "provisioning_model_value"} + }, + "size": 443, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # It is an error to provide an api_key and a transport instance. - transport = transports.AdviceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdviceClient( - client_options=options, - transport=transport, - ) + # Determine if the message type is proto-plus or protobuf + test_field = compute.CapacityAdviceRpcRequest.meta.fields[ + "capacity_advice_request_resource" + ] - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdviceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] - # It is an error to provide scopes and a transport instance. - transport = transports.AdviceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AdviceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + subfields_not_in_runtime = [] -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "capacity_advice_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["capacity_advice_request_resource"][field]) + ): + del request_init["capacity_advice_request_resource"][field][i][ + subfield + ] + else: + del request_init["capacity_advice_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.CapacityAdviceResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.CapacityAdviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.capacity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.CapacityAdviceResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_capacity_rest_interceptors(null_interceptor): transport = transports.AdviceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AdviceRestInterceptor(), ) client = AdviceClient(transport=transport) - assert client.transport is transport + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.AdviceRestInterceptor, "post_capacity") as post, + mock.patch.object( + transports.AdviceRestInterceptor, "post_capacity_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.AdviceRestInterceptor, "pre_capacity") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CapacityAdviceRpcRequest.pb( + compute.CapacityAdviceRpcRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -@pytest.mark.parametrize( - "transport_class", - [ - transports.AdviceRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.CapacityAdviceResponse.to_json( + compute.CapacityAdviceResponse() + ) + req.return_value.content = return_value + request = compute.CapacityAdviceRpcRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.CapacityAdviceResponse() + post_with_metadata.return_value = compute.CapacityAdviceResponse(), metadata -def test_transport_kind_rest(): - transport = AdviceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.capacity( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_calendar_mode_rest_bad_request( - request_type=compute.CalendarModeAdviceRpcRequest, +def test_capacity_history_rest_bad_request( + request_type=compute.CapacityHistoryAdviceRequest, ): client = AdviceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -1178,33 +1962,38 @@ def test_calendar_mode_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.calendar_mode(request) + client.capacity_history(request) @pytest.mark.parametrize( "request_type", [ - compute.CalendarModeAdviceRpcRequest, + compute.CapacityHistoryAdviceRequest, dict, ], ) -def test_calendar_mode_rest_call_success(request_type): +def test_capacity_history_rest_call_success(request_type): client = AdviceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2"} - request_init["calendar_mode_advice_request_resource"] = { - "future_resources_specs": {} + request_init["capacity_history_request_resource"] = { + "instance_properties": { + "machine_type": "machine_type_value", + "scheduling": {"provisioning_model": "provisioning_model_value"}, + }, + "location_policy": {"location": "location_value"}, + "types": ["types_value1", "types_value2"], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = compute.CalendarModeAdviceRpcRequest.meta.fields[ - "calendar_mode_advice_request_resource" + test_field = compute.CapacityHistoryAdviceRequest.meta.fields[ + "capacity_history_request_resource" ] def get_message_fields(field): @@ -1234,7 +2023,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime for field, value in request_init[ - "calendar_mode_advice_request_resource" + "capacity_history_request_resource" ].items(): # pragma: NO COVER result = None is_repeated = False @@ -1266,40 +2055,43 @@ def get_message_fields(field): if subfield: if field_repeated: for i in range( - 0, len(request_init["calendar_mode_advice_request_resource"][field]) + 0, len(request_init["capacity_history_request_resource"][field]) ): - del request_init["calendar_mode_advice_request_resource"][field][i][ + del request_init["capacity_history_request_resource"][field][i][ subfield ] else: - del request_init["calendar_mode_advice_request_resource"][field][ - subfield - ] + del request_init["capacity_history_request_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.CalendarModeAdviceResponse() + return_value = compute.CapacityHistoryResponse( + location="location_value", + machine_type="machine_type_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.CalendarModeAdviceResponse.pb(return_value) + return_value = compute.CapacityHistoryResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.calendar_mode(request) + response = client.capacity_history(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.CalendarModeAdviceResponse) + assert isinstance(response, compute.CapacityHistoryResponse) + assert response.location == "location_value" + assert response.machine_type == "machine_type_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_calendar_mode_rest_interceptors(null_interceptor): +def test_capacity_history_rest_interceptors(null_interceptor): transport = transports.AdviceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.AdviceRestInterceptor(), @@ -1310,18 +2102,20 @@ def test_calendar_mode_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.AdviceRestInterceptor, "post_calendar_mode" + transports.AdviceRestInterceptor, "post_capacity_history" ) as post, mock.patch.object( - transports.AdviceRestInterceptor, "post_calendar_mode_with_metadata" + transports.AdviceRestInterceptor, "post_capacity_history_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.AdviceRestInterceptor, "pre_calendar_mode") as pre, + mock.patch.object( + transports.AdviceRestInterceptor, "pre_capacity_history" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.CalendarModeAdviceRpcRequest.pb( - compute.CalendarModeAdviceRpcRequest() + pb_message = compute.CapacityHistoryAdviceRequest.pb( + compute.CapacityHistoryAdviceRequest() ) transcode.return_value = { "method": "post", @@ -1333,21 +2127,21 @@ def test_calendar_mode_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = compute.CalendarModeAdviceResponse.to_json( - compute.CalendarModeAdviceResponse() + return_value = compute.CapacityHistoryResponse.to_json( + compute.CapacityHistoryResponse() ) req.return_value.content = return_value - request = compute.CalendarModeAdviceRpcRequest() + request = compute.CapacityHistoryAdviceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.CalendarModeAdviceResponse() - post_with_metadata.return_value = compute.CalendarModeAdviceResponse(), metadata + post.return_value = compute.CapacityHistoryResponse() + post_with_metadata.return_value = compute.CapacityHistoryResponse(), metadata - client.calendar_mode( + client.capacity_history( request, metadata=[ ("key", "val"), @@ -1386,6 +2180,44 @@ def test_calendar_mode_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_capacity_empty_call_rest(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.capacity), "__call__") as call: + client.capacity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CapacityAdviceRpcRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_capacity_history_empty_call_rest(): + client = AdviceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.capacity_history), "__call__") as call: + client.capacity_history(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CapacityHistoryAdviceRequest() + assert args[0] == request_msg + + def test_advice_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -1407,7 +2239,11 @@ def test_advice_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. - methods = ("calendar_mode",) + methods = ( + "calendar_mode", + "capacity", + "capacity_history", + ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) @@ -1553,6 +2389,12 @@ def test_advice_client_transport_session_collision(transport_name): session1 = client1.transport.calendar_mode._session session2 = client2.transport.calendar_mode._session assert session1 != session2 + session1 = client1.transport.capacity._session + session2 = client2.transport.capacity._session + assert session1 != session2 + session1 = client1.transport.capacity_history._session + session2 = client2.transport.capacity_history._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py index d2ebd413ba2d..69027751fb47 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py @@ -3932,7 +3932,7 @@ def test_insert_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3978,7 +3978,7 @@ def test_insert_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4129,7 +4129,7 @@ def test_insert_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -4175,7 +4175,7 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5405,7 +5405,7 @@ def test_patch_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5452,7 +5452,7 @@ def test_patch_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5612,7 +5612,7 @@ def test_patch_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5659,7 +5659,7 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11734,7 +11734,9 @@ def test_insert_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"project": "sample1", "zone": "sample2"} request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -12718,7 +12720,9 @@ def test_patch_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py index 4a80cc0db8ee..bb8151d73545 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py @@ -3744,6 +3744,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py index b565d7936945..b1397d0d6992 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py @@ -20605,6 +20605,7 @@ def test_bulk_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, @@ -22758,6 +22759,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": {"enabled": True, "max_duration": {}}, "host_error_timeout_seconds": 2811, "instance_termination_action": "instance_termination_action_value", @@ -26520,6 +26522,7 @@ def test_set_scheduling_rest_call_success(request_type): request_init["scheduling_resource"] = { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, @@ -29134,6 +29137,7 @@ def test_update_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": {"enabled": True, "max_duration": {}}, "host_error_timeout_seconds": 2811, "instance_termination_action": "instance_termination_action_value", diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py index e479bf0e188a..e9e1b1e98de2 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py @@ -3701,6 +3701,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_project_views.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_project_views.py new file mode 100644 index 000000000000..3c63195a7d87 --- /dev/null +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_project_views.py @@ -0,0 +1,1650 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1.services.project_views import ( + ProjectViewsClient, + transports, +) +from google.cloud.compute_v1.types import compute + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ProjectViewsClient._get_client_cert_source(None, False) is None + assert ( + ProjectViewsClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ProjectViewsClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ProjectViewsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ProjectViewsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ProjectViewsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ProjectViewsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ProjectViewsClient, "rest"), + ], +) +def test_project_views_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ProjectViewsRestTransport, "rest"), + ], +) +def test_project_views_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ProjectViewsClient, "rest"), + ], +) +def test_project_views_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_project_views_client_get_transport_class(): + transport = ProjectViewsClient.get_transport_class() + available_transports = [ + transports.ProjectViewsRestTransport, + ] + assert transport in available_transports + + transport = ProjectViewsClient.get_transport_class("rest") + assert transport == transports.ProjectViewsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest"), + ], +) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +def test_project_views_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ProjectViewsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ProjectViewsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", "true"), + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_project_views_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ProjectViewsClient]) +@mock.patch.object( + ProjectViewsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectViewsClient) +) +def test_project_views_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [ProjectViewsClient]) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +def test_project_views_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ProjectViewsClient._DEFAULT_UNIVERSE + default_endpoint = ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest"), + ], +) +def test_project_views_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", None), + ], +) +def test_project_views_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_get_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get] = mock_rpc + + request = {} + client.get(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_rest_required_fields(request_type=compute.GetProjectViewRequest): + transport_class = transports.ProjectViewsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGet, + "_BaseGet__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ProjectView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_flattened(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.ProjectView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/projectViews" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetProjectViewRequest(), + project="project_value", + region="region_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProjectViewsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectViewsRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = ProjectViewsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetProjectViewRequest): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetProjectViewRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ProjectView.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.ProjectView) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectViewsRestInterceptor(), + ) + client = ProjectViewsClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.ProjectViewsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.ProjectViewsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.ProjectViewsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetProjectViewRequest.pb(compute.GetProjectViewRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.ProjectView.to_json(compute.ProjectView()) + req.return_value.content = return_value + + request = compute.GetProjectViewRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ProjectView() + post_with_metadata.return_value = compute.ProjectView(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_empty_call_rest(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get), "__call__") as call: + client.get(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetProjectViewRequest() + assert args[0] == request_msg + + +def test_project_views_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProjectViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_project_views_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.project_views.transports.ProjectViewsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ProjectViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("get",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_project_views_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.compute_v1.services.project_views.transports.ProjectViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectViewsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_project_views_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.compute_v1.services.project_views.transports.ProjectViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectViewsTransport() + adc.assert_called_once() + + +def test_project_views_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ProjectViewsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_project_views_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ProjectViewsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_project_views_host_no_port(transport_name): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_project_views_host_with_port(transport_name): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_project_views_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProjectViewsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProjectViewsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ProjectViewsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ProjectViewsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ProjectViewsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ProjectViewsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ProjectViewsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ProjectViewsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ProjectViewsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ProjectViewsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = ProjectViewsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ProjectViewsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ProjectViewsTransport, "_prep_wrapped_messages" + ) as prep: + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ProjectViewsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ProjectViewsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py index d1a80769a011..7cd0e3e62fac 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py @@ -3684,7 +3684,7 @@ def test_insert_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3730,7 +3730,7 @@ def test_insert_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3881,7 +3881,7 @@ def test_insert_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -3927,7 +3927,7 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5164,7 +5164,7 @@ def test_patch_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5211,7 +5211,7 @@ def test_patch_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5371,7 +5371,7 @@ def test_patch_unary_rest_flattened(): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -5418,7 +5418,7 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): instance_group_manager_resource=compute.InstanceGroupManager( all_instances_config=compute.InstanceGroupManagerAllInstancesConfig( properties=compute.InstancePropertiesPatch( - labels={"key_value": "value_value"} + expose_host_topology=True ) ) ), @@ -11365,7 +11365,9 @@ def test_insert_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2"} request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], @@ -12362,7 +12364,9 @@ def test_patch_rest_call_success(request_type): "instance_group_manager": "sample3", } request_init["instance_group_manager_resource"] = { - "all_instances_config": {"properties": {"labels": {}, "metadata": {}}}, + "all_instances_config": { + "properties": {"expose_host_topology": True, "labels": {}, "metadata": {}} + }, "auto_healing_policies": [ {"health_check": "health_check_value", "initial_delay_sec": 1778} ], diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py index 79b394018b0c..c31b1e168c9c 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py @@ -2740,6 +2740,7 @@ def test_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py index 86466717bc71..bd630e1b401c 100644 --- a/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py +++ b/preview-packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py @@ -1567,6 +1567,7 @@ def test_bulk_insert_rest_call_success(request_type): "scheduling": { "automatic_restart": True, "availability_domain": 2002, + "expose_host_topology": True, "graceful_shutdown": { "enabled": True, "max_duration": {"nanos": 543, "seconds": 751}, diff --git a/release-please-bulk-config.json b/release-please-bulk-config.json index 18a2d17ffb06..51ad4f3bd546 100644 --- a/release-please-bulk-config.json +++ b/release-please-bulk-config.json @@ -529,10 +529,16 @@ "extra-files": [ "google/cloud/backupdr/gapic_version.py", "google/cloud/backupdr_v1/gapic_version.py", + "google/cloud/backupdr_v1beta/gapic_version.py", { "jsonpath": "$.clientLibrary.version", "path": "samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json", "type": "json" + }, + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json", + "type": "json" } ] }, @@ -2261,10 +2267,16 @@ "extra-files": [ "google/cloud/network_services/gapic_version.py", "google/cloud/network_services_v1/gapic_version.py", + "google/cloud/network_services_v1beta1/gapic_version.py", { "jsonpath": "$.clientLibrary.version", "path": "samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json", "type": "json" + }, + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1beta1.json", + "type": "json" } ] }, @@ -3902,4 +3914,4 @@ } }, "release-type": "python-librarian" -} \ No newline at end of file +} diff --git a/release-please-individual-config.json b/release-please-individual-config.json index e720b656cb65..83209fc58e56 100644 --- a/release-please-individual-config.json +++ b/release-please-individual-config.json @@ -56,6 +56,9 @@ } ] }, + "packages/google-cloud-spanner-dbapi-driver": { + "component": "google-cloud-spanner-dbapi-driver" + }, "packages/google-cloud-sql": { "component": "google-cloud-sql", "extra-files": [